php多条件查询

比如一个查询系统,有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后面的查询条件就好了。



  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值