PHP 多条件查询(汽车表)

主页面:

 1 <h1>汽车查询页面</h1>
 2 <br />
 3 <?php
 4     include("./DBDA.class.php");
 5     $db = new DBDA();
 6     
 7     $cx="";
 8     $value="";
 9     
10     $tj1 = " 1=1"; //条件1的判断
11     $tj2 = " 1=1"; //条件2的判断
12     
13     if(!empty($_POST["name"]))
14     {
15         $tj1 = " Name like '%{$_POST['name']}%'";
16     }
17     if(!empty($_POST["brand"]))
18     {
19         $tj2 = " Brand = '{$_POST['brand']}'";
20     }
21     
22     $cx = " where {$tj1} and {$tj2} ";
23 ?>
24 <form action="test.php" method="post">
25 <div>
26     请输入名称:<input type="text" name="name" value="<?php echo $value; ?>" /> &nbsp;
27     系列:<input type="text" name="brand" />&nbsp;
28     <input type="submit" value="查询" />
29 </div>
30 </form>
31 <br />
32 <table width="100%" border="1" cellpadding="0" cellspacing="0">
33     <tr>
34         <td>代号</td>
35         <td>汽车名称</td>
36         <td>系列</td>
37         <td>价格</td>
38         <td>油耗</td>
39         <td>功率</td>
40     </tr>
41     
42     <?php
43 
44         $sql = "select * from Car".$cx;
45         $attr = $db->Query($sql);
46         echo $sql;
47         
48         foreach($attr as $v)
49         {
50             //处理Name
51             $rp = "<span style='color:red'>{$value}</span>";
52             $str = str_replace($value,$rp,$v[1]);
53             echo "<tr>
54                 <td>{$v[0]}</td>
55                 <td>{$str}</td>
56                 <td>{$v[2]}</td>
57                 <td>{$v[7]}</td>
58                 <td>{$v[4]}</td>
59                 <td>{$v[5]}</td>
60             </tr>";
61         }
62     
63     ?>
64     
65 </table>

封装类页面

<?php

class DBDA
{
    public $host = "localhost";    //数据库地址
    public $uid = "root";    //数据库用户名
    public $pwd = "123";    //数据库密码
    
    //执行SQL语句,返回相应的结果的方法
    //参数:$sql代表要执行的SQL语句,$type是SQL语句类型0代表查询1代表其他,$db代表要操作的数据库
    public function Query($sql,$type=0,$db="mydb")
    {
        //1.造连接对象
        $dbconnect = new MySQLi($this->host,$this->uid,$this->pwd,$db);
        //2.判断连接是否出错
        !mysqli_connect_error() or die("连接失败!");
        //3.执行SQL语句
        $result = $dbconnect->query($sql);
        
        if($type==0)
        {
            return $result->fetch_all();
        }
        else
        {
            return $result;
        }
    }
}
?>

 

posted @ 2016-05-09 21:57  冷风~云  阅读(267)  评论(0编辑  收藏  举报