PDO multiple named placeholders doesnt retrieve data

前端 未结 1 1435
星月不相逢
星月不相逢 2020-12-12 03:19

The code I\'ve written so far works fine if there is only one named place holder for a prepared statement but if there are multiple conditions for a query, it doesn\'t retur

相关标签:
1条回答
  • 2020-12-12 03:48

    bindParam Requires a reference

    The problem is caused by the way you bind parameters in the foreach loop.

    foreach($bindings as $placeholder=>$bound){
        echo $placeholder . " - " . $bound."<br/>";
        $stmt->bindParam($placeholder, $bound);
    }
    

    bindParam requires a reference. It binds the variable, not the value, to the statement. Since the variable in a foreach loop is reset at the start of each iteration, only the last reference to $bound is left intact, and you end up binding all your placeholders to it.

    That's why your code works when $query['where'] contains only one entry, but fails when it contains more than one.

    You can solve the problem in 2 ways:

    Pass by reference

    foreach($bindings as $placeholder => &$bound) {  //pass $bound as a reference (&)
        $stmt->bindParam($placeholder, $bound);     // bind the variable to the statement
    }
    

    Pass by value

    Use bindValue instead of bindParam:

    foreach($bindings as $placeholder => $bound) {  
        $stmt->bindValue($placeholder, $bound);     // bind the value to the statement
    }
    
    0 讨论(0)
提交回复
热议问题