php查詢及多條件查詢
更新時間:2017年02月26日 15:15:47 作者:我之姓冠你之名
本文給大家分享的是使用php實(shí)現(xiàn)單條件以及多條件查詢的代碼及示例,非常實(shí)用,有需要的小伙伴可以參考下
單條件查詢:
1.先要有一張表,顯示出表中的數(shù)據(jù):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標(biāo)題文檔</title> </head> <body> <table border="1" cellspacing="0" cellpadding="0"> <tr> <td width="200">編號</td> <td width="200">姓名</td> <td width="200">電話</td> <td width="200" >分組</td> </tr> <?php $db = new mysqli("localhost","root","12345678","heiheihei"); $sql = "select * from contacts"; $r = $db->query($sql); //傳值 while ($attr = $r->fetch_row()) { echo " <tr> <td>{$attr[0]}</td> <td>{$attr[1]}</td> <td>{$attr[2]}</td> <td>{$attr[3]}</td> </tr>"; } ?> </table> </body> </html>
上圖:
啥都沒改的一張表
2.再來個from表單,讓用戶輸入,點(diǎn)擊查詢:
<form action="shouye.php" method="post"> <div> 輸入名字:<input type="text" name="name"/> <input type="submit" value="查詢"/> </div> </form>
如圖:
3.建立關(guān)鍵字查詢:
<?php //實(shí)現(xiàn)兩個邏輯 //1.如果沒有post數(shù)據(jù).查所有的 //2.如果有post數(shù)據(jù).根據(jù)條件查 $db = new mysqli("localhost","root","12345678","heiheihei"); //連接數(shù)據(jù)庫 $tj = " 1 = 1 "; $name=""; //恒成立,如果沒有寫數(shù)據(jù),那就讓條件等于1=1,這個條件是查找所有的數(shù)據(jù) //如果你寫入數(shù)據(jù),按照數(shù)據(jù)查 if(!empty($_POST)) { $name = $_POST['name']; $tj = " name like '%{$name}%'"; } //將條件拼接到SQl語句 $sql = "select * from contacts WHERE {$tj}"; echo $sql; //查出來 $r = $db->query($sql); //傳值 if($r) //開始判斷 { //$attr已經(jīng)接收到了值,現(xiàn)在只需要獲取他的索引就行了 while ($attr = $r->fetch_row()) { //關(guān)鍵字特殊查詢 $str = str_replace($name,"<mark>{$name}</mark>",$attr[1]); //查找替換如ctrl+f //substr_replace(); 在指定位置替換 //substr(); 截取字符串 $gname = "select gname from groups WHERE gid='{$attr[3]}'"; //分組表中的gid,和我點(diǎn)擊的 $nresult = $db->query($gname); $gname = $nresult->fetch_row(); $nation = $gname[0]; echo " <tr> <td>{$attr[0]}</td> <td>{$str}</td> <td>{$attr[2]}</td> <td>{$nation}</td> ?>
圖:
多條件查詢:
前面照舊;
出了php的語句:
<?php //實(shí)現(xiàn)兩個邏輯 //1.如果沒有post數(shù)據(jù).查所有的 //2.如果有post數(shù)據(jù).根據(jù)條件查 $db = new mysqli("localhost","root","12345678","heiheihei"); //連接數(shù)據(jù)庫 $tj1 = " 1 = 1 "; $tj2 = " 1 = 1 ";//兩個條件的恒等 $name=""; //恒成立,如果沒有寫數(shù)據(jù),那就讓條件等于1=1,這個條件是查找所有的數(shù)據(jù) //如果你寫入數(shù)據(jù),按照數(shù)據(jù)查 if(!empty($_POST["name"])) //第一個條件的判斷(用到了模糊查詢) { $name = $_POST['name']; $tj1 = " name like '%{$name}%'"; } if(!empty($_POST["tel"])) { $tel = $_POST["tel"]; $tj2 = "tel = '$tel'"; } //將條件拼接到SQl語句 $sql = "select * from contacts WHERE {$tj1} AND {$tj2}";
效果圖:
這樣:有幾個條件就做幾個條件變量,第一個條件不為空就執(zhí)行的第一個條件,第二個條件不為空執(zhí)行的第二個條件,兩個都為空就是查尋所有的數(shù)據(jù)
相關(guān)文章
php給一組指定關(guān)鍵詞添加span標(biāo)簽的方法
這篇文章主要介紹了php給一組指定關(guān)鍵詞添加span標(biāo)簽的方法,涉及php正則替換的技巧,非常具有實(shí)用價值,需要的朋友可以參考下2015-03-03