gpt4 book ai didi

php - 当搜索参数值为 null 或为空时选择所有行 [mysql]

转载 作者:行者123 更新时间:2023-11-29 04:15:35 30 4
gpt4 key购买 nike

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

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

这是我的 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 条件。

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

最佳答案

可以在查询之前勾选过滤条件,像这样

$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");

关于php - 当搜索参数值为 null 或为空时选择所有行 [mysql],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49145263/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com