输入条件,进行筛选,得出答案
进行封装:(使用方便)
<?php class DBDA { public $host = "localhost"; public $uid = "root"; public $pwd = ""; //执行SQL语句的方法 //参数:$sql代表要执行的SQL语句,$type代表SQL语句类型,0代表的是查询,1代表的是增删改$db代表的是操作的数据库 public function Query($sql,$type=0,$db="mydb") { $dbconnect = new MySQLi($this->host,$this->uid,$this->pwd,$db); !mysqli_connect_error() or die("连接失败"); $result = $dbconnect->query($sql); if($type==0) { return $result->fetch_all(); } else { return $result; } } }
查询页面:(单条件查询)
<body> <h1>汽车查询页面</h1> <br /> <?php include("DBDA.class.php"); $db = new DBDA(); $cx=""; $value=""; if(!empty($_POST["name"])) { $name = $_POST["name"]; $cx = " where name like ‘%{$name}%‘";//查询字符串 $value = $name; } ?> <form action="chaxun.php" method="post"> <div> 请输入名称:<input type="text" name="name" value="<?php echo $value;?>"/> 请输入系列:<input type="text" name="brand"/> <input type="submit" value="查询"/> </div> <br/> </form> <table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr> <td>代号</td> <td>汽车名称</td> <td>价格</td> <td>油耗</td> <td>功率</td> </tr> <?php $sql = "select * from Car".$cx; $attr = $db->Query($sql); foreach($attr as $v) { //处理name $rp = "<span style=‘color:red‘>{$value}</span>"; $str = str_replace($value,$rp,$v[1]); echo "<tr> <td>{$v[0]}</td> <td>{$str}</td> <td>{$v[7]}</td> <td>{$v[4]}</td> <td>{$v[5]}</td> </tr>"; } ?> </table> </body
多条件查询:
<body> <h1>汽车查询页面</h1> <br /> <?php include("./DBDA.class.php"); $db = new DBDA(); $cx=""; $value=""; $tj1 = " 1=1";//条件1的判断 $tj2 = " 1=1"; if(!empty($_POST["name"])) { $tj1 = " Name like ‘%{$_POST[‘name‘]}%‘"; } if(!empty($_POST["brand"])) { $tj2 = " Brand = ‘{$_POST[‘brand‘]}‘"; } $cx = " where {$tj1} and {$tj2} ";//条件2的判断 ?> <form action="查询0506/chaxunduo.php" method="post"> <div> 请输入名称:<input type="text" name="name" value="<?php echo $value;?>"/> 请输入系列:<input type="text" name="brand" /> <input type="submit" value="查询"/> </div> <br/> </form> <table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr> <td>代号</td> <td>汽车名称</td> <td>价格</td> <td>油耗</td> <td>功率</td> </tr> <?php $sql = "select * from Car".$cx; echo $sql; $attr = $db->Query($sql); foreach($attr as $v) { //处理name $rp = "<span style=‘color:red‘>{$value}</span>"; $str = str_replace($value,$rp,$v[1]); echo "<tr> <td>{$v[0]}</td> <td>{$str}</td> <td>{$v[7]}</td> <td>{$v[4]}</td> <td>{$v[5]}</td> </tr>"; } ?> </table> </body>
时间: 2024-11-22 23:27:35