问题描述:

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 about them and selects "Any". Now I want to check this query against the DB records. I use a normal mysql query as in

$db_q = "Select * from table where row1 = '" . $A . "' and row2 = '" . $B . "' and row3 =

'" . $C . "'";

This works fine as long as the user enters anything specific for A,B,C (!= "any"). When "any" is selected, i get something like this: "Select * from table where row1 = "any/all" etc." I can't seem to figure out the correct syntax (if it's even possible) and I would like to avoid messy case distinction (if A == any, perform select; if B == empty.. and so on).

Any help is much appreciated.

网友答案:

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";
网友答案:

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.

网友答案:

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;
}
网友答案:

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/

相关阅读:
Top