【问题标题】:select all rows when search parameter value is null or empty [mysql]当搜索参数值为空或为空时选择所有行 [mysql]
【发布时间】:2018-03-07 06:10:52
【问题描述】:

我正在尝试使用多个搜索选项,用户可以选择多个选项来过滤记录。

当用户不选择过滤选项时,默认情况下应返回所有记录。

这是我的 SQL 查询:

$query = 
    sprintf("SELECT * FROM users_leave_request 
        where leave_from >= '$leave_from' 
        AND leave_to <= '$leave_to' 
        AND leave_status = '$leave_stat' 
        AND user_id = '$emp_id'");

    $result=$this->db->exec($query);

我打算做的是:

  1. 假设$leave_stat参数为空,则应返回所有leave_stat值的记录。
  2. 同样,如果$emp_id 为空,则应返回所有用户的记录。

这有点像在参数为空时禁用*extra AND* where 条件。

我可以使用单个查询来执行此操作,还是必须为此使用单独的查询? 很感谢任何形式的帮助。谢谢。

【问题讨论】:

  • 动态构建查询。如果你有一个值,只需添加任何条件。您还应该考虑使用参数化的Prepared Statements,而不是连接您的查询。

标签: php mysql sql


【解决方案1】:

可以在查询前检查过滤条件,像这样

$whrcondn="";

$whrcondn.=($leave_from)?" and leave_from > = '$leave_from'":"";

$whrcondn.=($leave_to)?" and leave_to < = '$leave_to'":"";

$whrcondn.=($leave_status)?" and leave_status  = '$leave_stat'":"";

$whrcondn.=($emp_id)?" and user_id ='$emp_id'":"";

$query =  sprintf("select * from users_leave_request where 1=1 $whrcondn");

【讨论】:

    【解决方案2】:

    看看这个简单的方法 添加这个条件

    if(!empty($leave_stat))
     {$x='leave_status';}
    else
     {$x='leave_status!';}
    
    if(!empty($leave_stat))
     {$y='user_id';}
    else
     {$y='user_id!';}
    

    然后将 leave_status 和 user_id 更改为 $x 和 $y,如下所示:

     $query = sprintf("SELECT * FROM users_leave_request 
        where leave_from >= '$leave_from' 
        AND leave_to <= '$leave_to' 
        AND '$x' = '$leave_stat' 
        AND '$y' = '$emp_id'");
    
    $result=$this->db->exec($query);
    

    祝你好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多