Search code examples
phpmysqlpdobindparam

HOW TO LOOP PHP'S PDO BIND PARAM


Im current creating my own query builder now and Im stuck with PDO's prepared statement. Isn't it possible to loop the the PDO's BindParam. I did it using foreach() but it's not working it only on works on the last data that the loop executed.

$sql = "SELECT * FROM users WHERE id = :a OR fname = :b";

$array = array(":a"=>"10002345", "Josh");
$stmt = $conn->prepare($sql); 

foreach($array as $key => $value ) {
    $stmt->bindParam($key, $value);
}

$stmt->execute();

it only binds the last data executed by the loop.


Solution

  • It is better to simply pass your array to execute:

    $sql = "SELECT * FROM users WHERE id = :a OR fname = :b";
    $array = array("a" => "10002345", "b" => "Josh");
    $stmt = $conn->prepare($sql); 
    $stmt->execute($array);
    

    Or you can do it even simpler with ? placeholders:

    $sql = "SELECT * FROM users WHERE id = ? OR fname = ?";
    $array = array("10002345", "Josh"); // you don't even need keys here
    $stmt = $conn->prepare($sql);
    $stmt->execute($array);