PHP and MySQL optional WHERE conditions

后端 未结 4 2069
心在旅途
心在旅途 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: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.

提交回复
热议问题