Warning: PDO::prepare(): SQLSTATE[42000]: Syntax error or access violation: 1064 when update

橙三吉。 提交于 2020-01-06 06:50:46

问题


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=? WHERE id=?'

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!