I have the following problem: I want to let a user apply filters to a DB search. I have three filters, A, B and C. All of them can be \"empty\", as in, the user doesn\'t care a
Try doing something like this:
if @param1 is not null
select * from table1 where col1 = @param1
else
select * from table1 where col2 = @param2
This can be rewritten:
select * from table1
where (@param1 is null or col1 = @param1)
and (@param2 is null or col2 = @param2)
Got the idea from Baron Schwartz's blog: https://www.xaprb.com/blog/2005/12/11/optional-parameters-in-the-where-clause/
Before your query you could use:
$tmp = "where ";
if($A and $A!="any" and $A!="not used")
$tmp .= "row1 = '".$A."'";
if($B and $B!="any" and $B!="not used")
$tmp .= "AND row2 = '".$B. "'";
if($C and $C!="any" and $C!="not used")
$tmp .= "AND row3 = '".$C."'";
$db_q = "Select * from table $tmp";
Try this:
$db_q = "Select * from table ";
if ($A != "any" || $B != "any" || $C != "any")
{
$db_q .= "where ";
}
$firstCondition = true;
if ($A != "any")
{
if (!$firstCondition)
$db_q .= "and ";
$db_q .= "row1 = '$A' ";
$firstCondition = false;
}
if ($B != "any")
{
if (!$firstCondition)
$db_q .= "and ";
$db_q .= "row2 = '$B' ";
$firstCondition = false;
}
if ($C != "any")
{
if (!$firstCondition)
$db_q .= "and ";
$db_q .= "row3 = '$C' ";
$firstCondition = false;
}
The other answers are mostly correct, but this is a simpler way to accomplish what is needed:
$where = array();
if($A != 'any'){ // or whatever you need
$where[] = "A = $A'";
}
if($B != 'any'){ // or whatever you need
$where[] = "B = $B'";
}
if($C != 'any'){ // or whatever you need
$where[] = "C = $C'";
}
$where_string = implode(' AND ' , $where);
$query = "SELECT * FROM table";
if($where){
$query .= ' ' . $where_string;
}
This will allow for any combination of conditions and expansion.