Reputation: 935
I'm getting the following errors when trying to loop through an array on my server to bind statements with PDO:
"Only variables can be passed by reference" or "Cannot pass parameter 2 by reference pdo"
Works fine on my local XAMPP.
Code:
$sql = rest of sql query etc.
$loop = 1;
foreach ($animal_array $ani)
{
if ($loop == 1) {$sql .= " WHERE animal.id= :animal_id".$loop; }
else {$sql .= " OR animal.id= :animal_id".$loop;}
$loop++;
}
$stmt = $crud->db->prepare($sql);
$loop = 1;
foreach ($animal_array as $ani)
{
$stmt->bindParam(':animal_id'.$loop, $ani['animal_id'], PDO::PARAM_STR);
$loop++;
}
Also tried this at the end as I read somewhere that concatonations sometimes aren't liked:
foreach ($animal_array as $ani)
{
$ref = ":animal_id".$loop;
$stmt->bindParam($ref, $ani['animal_id'], PDO::PARAM_STR);
$loop++;
}
.
EDIT: The array contains other values, sort of like this:
$animal_array['animal_id'];
$animal_array['name'];
$animal_array['colour'];
$animal_array['quantity']; etc
Upvotes: 1
Views: 870
Reputation: 125925
It feels like you're overcomplicating matters... why not just pass the array to execute
directly:
$sql .= 'WHERE animal.id IN ('
. '?'.str_repeat(',?', count($animal_array['animal_id'])-1)
. ')';
$qry = $crud->db->prepare($sql);
$qry->execute($animal_array['animal_id']);
Upvotes: 1
Reputation: 145482
You ought to use bindValue
for pure input parameters. The bindParam
method is reserved for binding variables which can be used as input but also return query results (output).
Though that doesn't explain your issue. But we don't know what your array contains.
It's not the key generation / concatenation for sure.
Upvotes: 2