Writing a query that contains variable WHERE based on user input

后端 未结 2 851
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 05:40

I\'m having trouble with a query. What I would like it to do is check that each variable exists, and ignore them if they don\'t. I also want to display the results in a table. A

2条回答
  •  梦谈多话
    2021-01-22 06:32

    The OR condition requires that any of the conditions (ie: condition1, condition2, condition_n) be must be met for the record to be included in the result set.Whereas the AND condition requires that all of the conditions (ie: condition1, condition2, condition_n) be must be met. For your requirement the OR condition is required.

    You need to build a dynamic query to perform this. Start with a basic stub

    $sql = "SELECT * FROM customer";
    

    Then you need to set the initial clause to WHERE.

    $clause = " WHERE ";//Initial clause
    

    You need an array to store parameters

    $paramArray =array();
    

    Start building the query.Note I have changed from POST to GET as it is easier to test Also see PDO WIKI for use % in placeholders.ie placeholders cannot represent an arbitrary part of the query, but a complete data literal only.

    if(isset($_GET['First_name'])){
        $First_name = $_GET['First_name'];
        $sql .= "$clause First_name LIKE ?";
        $clause = " OR ";//Change clause
        array_push($paramArray,"%$First_name%");
    }   
    

    Continue with next clause

    if(isset($_GET['Surname'])){
        $Surname = $_GET['Surname'];
        $sql .= "$clause Surname LIKE ?";
        $clause = " OR ";
        array_push($paramArray,"%$Surname%");
    }   
    

    Add remainder of clauses as above

    Test result, Remove after testing & change GET to POST

    echo $sql ;
    echo "
    "; print_r($paramArray);

    Prepare and execute query

    $sth = $db->prepare($sql);
    $sth->execute($paramArray);
    

    Typical Test Result from test.php?First_name=dave&Surname=smith

    SELECT * FROM customer WHERE First_name LIKE ? OR Surname LIKE ?
    Array ( [0] => %dave% [1] => %smith% )
    

    from test.php?Surname=smith

    SELECT * FROM customer WHERE Surname LIKE ?
    Array ( [0] => %smith% )
    

提交回复
热议问题