標籤:表單 remove cell tin php 點擊 類型 require 設定
租房子例題是用來練習多條件查詢以及批量選擇的典型例題,題面是這樣的:
首先要分別建立地區、租賃類型、房屋類型的複選介面,遍曆出所有資料,這裡用無邊框表格建立:
<table width="100%" cellpadding="0" cellspacing="0"> <tr> <td>地區:<input type="checkbox" name="qx" onclick="quanxuan(this,‘ck‘)" />全選</td><!--設定複選框和點擊事件,為批量選擇做準備--> </tr> </table> <?php $sql1 = "select distinct area from house";//去重查詢 $arr1 = $db->query($sql1); foreach($arr1 as $v) { echo "<tr> <td><input type=‘checkbox‘ name=‘ck[]‘ class=‘ck‘ value=‘{$v[0]}‘ />{$v[0]}</td> </tr>";//遍曆出複選框內容,ck[]是一個數組 } ?><br /><br /><table width="100%" cellpadding="0" cellspacing="0"> <tr> <td>租賃類型:<input type="checkbox" name="qx1" onclick="quanxuan(this,‘ck1‘)" />全選</td> </tr> </table> <?php $sql2 = "select distinct renttype from house"; $arr2 = $db->query($sql2); foreach($arr2 as $v) { echo "<tr> <td><input type=‘checkbox‘ name=‘ck1[]‘ class=‘ck1‘ value=‘{$v[0]}‘ />{$v[0]}</td> </tr>"; } ?><br /><br /> <table width="100%" cellpadding="0" cellspacing="0"> <tr> <td>房屋類型:<input type="checkbox" name="qx2" onclick="quanxuan(this,‘ck2‘)" />全選</td> </tr> </table> <?php $sql3 = "select distinct housetype from house"; $arr3 = $db->query($sql3); foreach($arr3 as $v) { echo "<tr> <td><input type=‘checkbox‘ name=‘ck2[]‘ class=‘ck2‘ value=‘{$v[0]}‘ />{$v[0]}</td> </tr>"; } ?><br />
然後再用表單做搜尋方塊,並用表格輸出表中資料:
<div>關鍵字:<input type="text" name="keyword" value="<?php echo $keyword ?>" /><input type="submit" value="搜尋" /></div> <br /> <table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr> <td>關鍵字</td> <td>地區</td> <td>面積</td> <td>租金</td> <td>租賃類型</td> <td>房屋類型</td> </tr><?php$arr=$db->query($sql);foreach($arr as $v){ $str=str_replace($keyword,"<span style=‘color:red‘>{$keyword}</span>",$v[1]);//尋找替換關鍵詞變為紅色 echo"<tr> <td>{$str}</td> <td>{$v[2]}</td> <td>{$v[3]}</td> <td>{$v[4]}</td> <td>{$v[5]}</td> <td>{$v[6]}</td> </tr>";}?></table>
然後用JS設定全選模式,上邊在onclick裡邊設定了兩個參數,是為了用一個函數來將地區、租賃類型、房屋類型的全選都做出來:
function quanxuan(qx,a){ //找到該全選按鈕對應的checkbox列表 var c=document.getElementsByClassName(a); //找全選按鈕選中狀態 if(qx.checked) { for(var i=0; i<c.length;i++) { c[i].setAttribute("checked","checked");//添加已選 } } else{ for(var i=0;i<c.length;i++) { c[i].removeAttribute("checked");//去除已選 } }}</script>
最後就是多條件查詢:
<?phprequire "DBDA.class.php";$db=new DBDA();$keyword="";$tj1=" 1=1 ";//多條件查詢,一定空格$tj2=" 1=1 ";$tj3=" 1=1 ";$tj4=" 1=1 ";if(!empty($_POST["keyword"]))//判斷是否為空白{ $keyword=$_POST["keyword"];//提取資料 $tj1=" keyword like ‘%{$keyword}%‘ ";//設定條件}if(!empty($_POST["ck"])){ $arr4=$_POST["ck"]; $str=implode("‘,‘",$arr4);//數組組成字串 $tj2=" area in (‘{$str}‘) ";}if(!empty($_POST["ck1"])){ $arr5=$_POST["ck1"]; $str=implode("‘,‘",$arr5); $tj3=" renttype in (‘{$str}‘) ";}if(!empty($_POST["ck2"])){ $arr6=$_POST["ck2"]; $str=implode("‘,‘",$arr6); $tj4=" housetype in (‘{$str}‘) ";}$tj=" {$tj1}and{$tj2}and{$tj3}and{$tj4} ";$sql="select * from house where".$tj;?>
切記:所有代碼都要在一個form表單中:
<form action="house.php" method="post"></form><!--要將所有代碼嵌套在form表單中-->
php租房子批量搜尋例題