PHP and MySQL optional WHERE conditions

后端 未结 4 2070
心在旅途
心在旅途 2021-01-29 09:59

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

相关标签:
4条回答
  • 2021-01-29 10:01

    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/

    0 讨论(0)
  • 2021-01-29 10:02

    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";
    
    0 讨论(0)
  • 2021-01-29 10:18

    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;
    }
    
    0 讨论(0)
  • 2021-01-29 10:28

    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.

    0 讨论(0)
提交回复
热议问题