比如一个查询系统,有5个条件让你输入,你只输其中的一个或者几个,这样的where怎么写。
让我自己想的时候,我想了很多if嵌套,然后把自己绕晕了,就放弃了。
在网上看了一下别人怎么做,在这里总结一下。
<?php
require('side.php');
$con= mysql_connect("localhost","root","root");
if(!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("db",$con);
mysql_query("SET NAMES 'UTF8'");
$account = isset($_REQUEST['account'])?($_REQUEST['account']):"";
$name = isset($_REQUEST['name'])?($_REQUEST['name']):"";
$idnum = isset($_REQUEST['idnum'])?($_REQUEST['idnum']):"";
$phonenum = isset($_REQUEST['phonenum'])?($_REQUEST['phonenum']):"";
$trainnum = isset($_REQUEST['trainnum'])?($_REQUEST['trainnum']):"";
if (!empty($account)) {
$where = " and colum_15 = '{$account}'";
}
if(!empty($name)) {
$where .= " and colum_16 = '{$name}'";
}
if (!empty($idnum)) {
$where .= " and colum_20 = '{$idnum}'";
}
if (!empty($phonenum)) {
$where .= " and colum_21 = '{$phonenum}'";
}
if (!empty($trainnum)) {
$where .= " and colum_7 = '{$trainnum}'";
}
$sql = "select * from police where 1 $where ";
$query =mysql_query($sql);
while($result= mysql_fetch_array($query)){
$data[]=$result;
}
?>
有一个问题,就是只有一个条件的时候,where又不晓得这个条件是第一个 where后面有没有and就很难处理。
所以在这里就先写一个where 1, 一个肯定为真的条件,然后再and后面的查询条件就好了。