您的位置:首页 > 编程语言 > PHP开发

php多条件查询

2015-07-20 10:28 513 查看
比如一个查询系统,有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又不晓得这个条件是第一个 where后面有没有and就很难处理。

所以在这里就先写一个where 1, 一个肯定为真的条件,然后再and后面的查询条件就好了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: