I am trying to use multiple search options where user can select multiple options to filter records.
When user don't select filter option(s), by default all records should be returned.
Here's my SQL query :
$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);
What I intend to do is that:
$leave_stat
parameter is empty, then records for all leave_stat
values should be returned. $emp_id
is empty, records for all users should be returned. It's somewhat like disabling that *extra AND*
where condition when parameter is empty.
Can I do this with a single query or do I have to use separate queries for that? Any help is very much appreciated. Thanks.
You can check the filter condition before the query, like this
$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");
look at this simple way add this condition
if(!empty($leave_stat))
{$x='leave_status';}
else
{$x='leave_status!';}
if(!empty($leave_stat))
{$y='user_id';}
else
{$y='user_id!';}
then change leave_status and user_id by $x and $y like this :
$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);
and good luck
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.