I am attempting to UPDATE records within my MySQL database.
I build the prepared statement using arrays / loops:
$sql = "UPDATE table01 SET ";
foreach($values as $value)
{
$sql .="$value = :$value, ";
}
$sql = rtrim($sql,', ');
$sql .=" WHERE id = '$id'";
then I prepare this statement:
try
{
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare($sql);
Then I bind each of the tokens / placeholders in the prepared statement to the values to be inserted using another loop:
foreach(array_combine($values, $variables) as $value=>$variable)
{
$stmt->bindParam(':$value', $variable);
}
$stmt->execute();
where $values is an array of column headers in the database (therefore ':$value' is a set of token names corresponding to them) and $variables is an array of variables containing data to be stored.
When I run this, I am given the error:
Error: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
But as you can see I'm forming them from arrays - I've done counts on the arrays to ensure the elements match 1:1 and they do:
FYI:
$count1 = count($values);
$count2 = count($variables);
echo $count1;
echo $count2;
gives: 7575
(they both have 75 elements in them)