问题
I want to update several tables as below:
for ($i=0; $i <count($tablesnames); $i++) {
$update3=$pdo->prepare('UPDATE :surveytable SET `postrecords`=:newrecord WHERE `id`=:id');
//var_dump()here
$update3->bindValue(':surveytable', $tablesnames[$i],PDO::PARAM_STR);
$update3->bindValue(':newrecord',$newrecord,PDO::PARAM_STR);
$update3->bindValue(':id',$id,PDO::PARAM_INT);
$update3->execute();
}
Check the var_dump result,$tablesnames[$i] and $newrecordare string,$id is int,$update3 is false.
Seemed everything ok but failed,
Warning: PDO::prepare(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? SET
postrecords=? WHEREid=?'
What's the problem?
回答1:
(Unfortunately) you can't use parameters for your tablename in your prepared statement. You can only use those for data literals. So UPDATE :surveytable is invalid.
As per manual:
Parameter markers can represent a complete data literal only. Neither part of literal, nor keyword, nor identifier, nor whatever arbitrary query part can be bound using parameters.
When you (completely!!!) trust your source of $tablesnames, use
'UPDATE `' . $tablesnames[i]` . '` SET `postrecords`=:newrecord WHERE `id`=:id'
instead
来源:https://stackoverflow.com/questions/50087546/warning-pdoprepare-sqlstate42000-syntax-error-or-access-violation-1064