PHP and MySQL optional WHERE conditions

后端 未结 4 2115
心在旅途
心在旅途 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: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;
    }
    

提交回复
热议问题