PHP和MySQL可选WHERE条件

时间:2013-03-04 22:08:20

标签: php mysql select where

我遇到以下问题:我想让用户将过滤器应用于数据库搜索。 我有三个过滤器,A,B和C.它们都可以是空的",因为用户不关心它们并选择" Any"。现在我想针对数据库记录检查此查询。我在

中使用普通的mysql查询
$db_q = "Select * from table where row1 = '" . $A . "' and row2 = '" . $B . "' and row3 =
'" . $C . "'";

只要用户输入A,B,C特定的任何内容(!="任何"),这都可以正常工作。当"任何"被选中,我得到这样的结果:"从表中选择*,其中row1 =" any / all"等&#34。我似乎无法弄清楚正确的语法(如果它甚至可能)并且我想避免凌乱的案例区分(如果A == any,执行select;如果B == empty ..和等等。)

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:3)

其他答案大多是正确的,但这是完成所需工作的更简单方法:

$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;
}

这将允许任何条件和扩展的组合。

答案 1 :(得分:0)

在查询之前,您可以使用:

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

答案 2 :(得分:0)

试试这个:

$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;
}

答案 3 :(得分:0)

尝试做这样的事情:

if @param1 is not null
   select * from table1 where col1 = @param1
else
   select * from table1 where col2 = @param2

这可以改写:

select * from table1
where (@param1 is null or col1 = @param1)
  and (@param2 is null or col2 = @param2)

来自Baron Schwartz的博客:https://www.xaprb.com/blog/2005/12/11/optional-parameters-in-the-where-clause/