PHP 多條件查詢

PHP+Mysql多條件多值查詢示例代碼:php

index.html代碼:html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
 
< html >
< head >
< meta  http-equiv = "Content-Type"  content = "text/html; charset=UTF-8" >
< title >SQL多條件查詢示例</ title >
</ head >
< body >
< form  method = "post"  action = "deal.php" >
< h1 >房屋出租</ h1 >
房屋類型:< select  name = "type" >
< option  value = "1" >一居室</ option >
< option  value = "2" >二居室</ option >
< option  value = "3" >三居室</ option >
</ select >
面積:< input  name = "area"  type = "text" />
地址:< input  name = "addr"  type = "text" />
< input  name = "btn"  type = "submit"  value = "搜索"  />
</ form >
</ body >
</ html >

deal.php文件:mysql

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
<?php
//鏈接數據庫
$conn =mysql_connect( "localhost" , "root" , "" );
 
//選擇數據庫
$db =mysql_select_db( "數據庫名" );
 
//接收 參數
$type = $_POST [ 'type' ];
$area = $_POST [ 'area' ];
$addr = $_POST [ 'addr' ];
 
//SQL語句主題
$query = "select * from room  where "
 
//根據條件和傳的值拼接sql語句
//判斷面積不爲空
if ( $type != "" ){
     //而後根據具體面積分狀況拼接
     switch ( $type ){
         case  1:
             //一居室
             $query .= " room_type=1"
             break ;
         case  2:
             $query .= " room_type=2" ;
             break ;
         case  3:
             $query .= " room_type=3" ;
             break ;
     }
}
 
//面積
if ( $area != "" ){
     $query .= " and area ={$area}" ;
}
 
//地址
if ( $addr != "" ){
     $query .= " and addr like '%{$addr}%'" //地址
}
 
//執行查詢
$result =mysql_query( $query );
 
//遍歷結果
echo  "搜搜結果以下:" ;
while ( $row =mysql_fetch_array( $result )){
     
     echo  "地址:" . $row [ 'addr' ];
     echo  "" ;
     echo  "面積:" . $row [ 'area' ];
     echo  "" ;
     echo  "居室:" . $row [ 'type' ];
     echo  "" ;
     echo  "價格:" . $row [ 'addr' ];
     echo  "" ;
     //等等
}
 
?>
相關文章
相關標籤/搜索