租房时搜索练习:
例如 58同城 赶集网 一样租房子一类的网站,多条件搜索房子
第一:连接数据库,以复选框在前端页面显示各种条件
<h1>房屋搜索</h1> <form action="fzss.php" method="post"> <br /> <div> 区 域:<input type="checkbox" onclick="checkall(this,'qy')" />全选 <br /> <?php $sql="select distinct area from house"; $attr=$db->Query($sql); foreach($attr as $v) { echo "<input type='checkbox' class='qy' name='xx[]' value='{$v[0]}'/>{$v[0]} "; } ?> </div> <br /> <div> 租赁类型:<input type="checkbox" onclick="checkall(this,'zl')" />全选 <br /> <?php $sqlzl="select distinct renttype from house"; $attrzl=$db->Query($sqlzl); foreach($attrzl as $v) { echo "<input type='checkbox' class='zl' name='zz[]' value='{$v[0]}'/>{$v[0]} "; } ?> </div> <br /> <div> 房屋类型:<input type="checkbox" onclick="checkall(this,'fw')" />全选 <br /> <?php $sqlfw="select distinct housetype from house"; $attrfw=$db->Query($sqlfw); foreach($attrfw as $v) { echo "<input type='checkbox' class='fw' name='ff[]' value='{$v[0]}'/>{$v[0]} "; } ?> </div> <br /> <div> 关 键 字:<input type="text" name="gg"/> </div> <br /> <input type="submit" value="搜索" name="sousuo"/> </form>
javascript创建函数,点击 “全选” 时,能够全部选择,代码如下
<script type="text/javascript"> function checkall(a,b) { var qx=a.checked; var ck=document.getElementsByClassName(b); for(var i=0;i<ck.length;i++) { ck[i].checked=qx; } } </script>
第二步:后台处理代码
<?php include("SOUSUO.class.php"); $db=new SOUSUO(); $tjqy="1=1"; $tjzl="1=1"; $tjfw="1=1"; $tjgj="1=1"; $value=""; if(!empty($_POST["xx"])) { $attqy=$_POST["xx"]; $strqy=implode("','",$attqy); //区域搜索的方式 $tjqy="area in ('{$strqy}')"; } if(!empty($_POST["zz"])) { $attzl=$_POST["zz"]; $strzl=implode("','",$attzl); //租赁类型 $tjzl="renttype in ('{$strzl}')"; } if(!empty($_POST["ff"])) { $attfw=$_POST["ff"]; $strfw=implode("','",$attfw); //房屋类型 $tjfw="housetype in ('{$strfw}')"; } if(!empty($_POST["gg"])) //关键字 { $attgj=$_POST["gg"]; $tjgj="keyword like '%{$attgj}%'"; $value=$attgj; } $cx=" where {$tjqy} and {$tjzl} and {$tjfw} and {$tjgj}"; ?> <table width="1000px" cellpadding="0" cellspacing="0" border="1px"> <tr align='center'> <td>关键字</td> <td>区域</td> <td>建筑面积</td> <td>租金</td> <td>租赁</td> <td>房屋类型</td> </tr> <?php $sql2="select * from house".$cx; $attr2=$db->Query($sql2); foreach($attr2 as $v) { //将$v[1]中的关键字变成红色 $rp="<span style='color:red'>{$value}</span>"; $gj=str_replace($value,$rp,$v[1]); echo "<tr align='center'> <td>{$gj}</td> <td>{$v[2]}</td> <td>{$v[3]}</td> <td>{$v[4]}</td> <td>{$v[5]}</td> <td>{$v[6]}</td> </tr>"; } ?> </table>