php数据访问-查询
输入关键字效果
1 <body> 2 <h1>汽车信息</h1> 3 <?php 4 require"DBDA.class1.php";//$type 代表SQL语句的类型,0代表增删改,1代表查询 5 $db = new DBDA(); 6 7 //如果没有提交数据,显示所有 8 //如果有提交数据,根据关键字查询显示 9 $name = ""; 10 $tj1 = " 1=1 ";//第一个条件,对应名称,注意空格 11 $tj2 = " 1=1 ";//第二个条件,对应系列,注意空格 12 if(!empty($_POST["name"])) 13 { 14 $name = $_POST["name"]; 15 $tj1 = " name like '%{$name}%'"; 16 } 17 if(!empty($_POST["brand"])) 18 { 19 $brand = $_POST["brand"]; 20 $tj2 = " brand like '%{$brand}%'"; 21 } 22 //总条件 23 $tj ="{$tj1} and {$tj2}"; 24 $sql = "select * from car where ".$tj;//注意where后空格 25 /*echo $sql;*/ 26 ?> 27 <form action="chaxun.php" method="post"> 28 <div>名称:<input type="text" name="name" value="<?php echo $name ?>"/>系列:<input type="text" name="brand"/><input type="submit" value="查询" /></div> 29 </form> 30 <br/> 31 <table width="100%" border="1" cellpadding="0" cellspacing="0"> 32 <tr> 33 <td>代号</td> 34 <td>名称</td> 35 <td>系列</td> 36 <td>上市时间</td> 37 <td>价格</td> 38 </tr> 39 <?php 40 41 //只适用于单条件查询 42 /*$sql = "select * from car"; 43 $name=""; 44 if(!empty($_POST["name"])) 45 { 46 $name = $_POST["name"]; 47 $sql = "select * from car where name like '%{$name}%' "; 48 }*/ 49 50 $arr = $db->query($sql); 51 foreach($arr as $v) 52 { 53 $str = str_replace($name,"<span style='color:red'>{$name}</span>",$v[1]); 54 echo "<tr> 55 <td>{$v[0]}</td> 56 <td>{$str}</td> 57 <td>{$v[2]}</td> 58 <td>{$v[3]}</td> 59 <td>{$v[7]}</td> 60 </tr>"; 61 } 62 ?> 63 </table> 64 </body> 65 </html>
所引用的封装类
1 <?php 2 class DBDA 3 { 4 public $host = "localhost"; 5 public $uid = "root"; 6 public $pwd = "123"; 7 public $dbname = "newssystem"; 8 //执行SQL语句返回相应的结果 9 //$sql 要执行的SQL语句 10 //$type 代表SQL语句的类型,0代表增删改,1代表查询 11 function query($sql,$type=1) 12 { 13 $db = new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname); 14 15 $result = $db->query($sql); 16 17 if($type) 18 { 19 //如果是查询,显示数据 20 return $result->fetch_all(); 21 } 22 else 23 { 24 //如果是增删改,返回true或者false 25 return $result; 26 } 27 } 28 }