Only just stumbled across this, but just for future reference...
Firstly, I'll work on the assumption that your example was supposed to read $array = array(":a"=>"10002345", ":b"=>"Josh");
, as there would be an issue even if your :b
key was absent.
In this bit:
foreach($array as $key => $value ) {
$stmt->bindParam($key, $value);
}
You haven't 'passed by reference'. The $value
should be amended to &$value
foreach($array as $key => &$value ) {
$stmt->bindParam($key, $value);
}
This is because the bindParam
method signature requires the value to be a variable reference:
public function bindParam ($parameter, &$variable, $data_type = PDO::PARAM_STR, $length = null, $driver_options = null) {}
(note the &
before $variable
).
The end result of your original query (sans &
) is that all :params
would be set to the value that is in the last iteration of $value
in your original loop.
So, the result of
$sql = "SELECT * FROM users WHERE id = :a OR fname = :b";
$array = array(":a"=>"10002345", ":b"=>"Josh");
$stmt = $conn->prepare($sql);
foreach($array as $key => $value ) {
$stmt->bindParam($key, $value);
}
$stmt->execute();
Would be SELECT * FROM users WHERE id = 'Josh' OR fname = 'Josh'
Using named parameters (:param
) has advantages over positional params (?
), so it's worth reserving that option for prepared statements, as opposed to the accepted answer of "it's better to use ?
placeholders", which is not the case.