本文实例为大家分享了php实现查询功能的具体代码,供大家参考,具体内容如下
输入关键字效果
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
<body> <h1>汽车信息</h1> <?php require "dbda.class1.php" ; //$type 代表sql语句的类型,0代表增删改,1代表查询 $db = new dbda(); //如果没有提交数据,显示所有 //如果有提交数据,根据关键字查询显示 $name = "" ; $tj1 = " 1=1 " ; //第一个条件,对应名称,注意空格 $tj2 = " 1=1 " ; //第二个条件,对应系列,注意空格 if (! empty ( $_post [ "name" ])) { $name = $_post [ "name" ]; $tj1 = " name like '%{$name}%'" ; } if (! empty ( $_post [ "brand" ])) { $brand = $_post [ "brand" ]; $tj2 = " brand like '%{$brand}%'" ; } //总条件 $tj = "{$tj1} and {$tj2}" ; $sql = "select * from car where " . $tj ; //注意where后空格 /*echo $sql;*/ ?> <form action= "chaxun.php" method= "post" > <div>名称:<input type= "text" name= "name" value= "<?php echo $name ?>" />系列:<input type= "text" name= "brand" /><input type= "submit" value= "查询" /></div> </form> <br/> <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"; $name=""; if(!empty($_post["name"])) { $name = $_post["name"]; $sql = "select * from car where name like '%{$name}%' "; }*/ $arr = $db ->query( $sql ); foreach ( $arr as $v ) { $str = str_replace ( $name , "<span style='color:red'>{$name}</span>" , $v [1]); echo "<tr> <td>{ $v [0]}</td> <td>{ $str }</td> <td>{ $v [2]}</td> <td>{ $v [3]}</td> <td>{ $v [7]}</td> </tr>"; } ?> </table> </body> </html> |
所引用的封装类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<?php class dbda { public $host = "localhost" ; public $uid = "root" ; public $pwd = "123" ; public $dbname = "newssystem" ; //执行sql语句返回相应的结果 //$sql 要执行的sql语句 //$type 代表sql语句的类型,0代表增删改,1代表查询 function query( $sql , $type =1) { $db = new mysqli( $this ->host, $this ->uid, $this ->pwd, $this ->dbname); $result = $db ->query( $sql ); if ( $type ) { //如果是查询,显示数据 return $result ->fetch_all(); } else { //如果是增删改,返回true或者false return $result ; } } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。