我在运行PDO执行时遇到问题,并以MySQL语法返回错误。
代码如下:
try {
global $connect;
$arr = array(':ranked' => $db_rank, ':tier' => $db_tier, ':id' => $_SESSION['user_id']);
$query = $connect->prepare('UPDATE users SET :ranked = :tier WHERE id = :id');
$query->execute($arr);
} catch (PDOException $e) {
echo $e->getMessage();
}
其中$ db_rank返回一个具有列名的字符串(从json转换),而$ db_tier返回一个连接的字符串(再次从json转换)。
它位于循环中,该循环应更新1-3列,但在执行时会引发异常:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''<column name1>' = '<value1>' WHERE id = '3'' at line 1
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''<column name2>' = '<value2>' WHERE id = '3'' at line 1
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''<column name3>' = '<value3>' WHERE id = '3'' at line 1
可能应该是因为将表列作为变量传递的,在这种情况下,我应该如何继续使用3个不同的预设表名循环它而不用使它成为意大利面条式代码?
答案 0 :(得分:0)
找到了我的答案:
应该用“而不是'来准备语句,因为在数组内部,类型会更改3次(一次是从函数开始,一次是通过传递,一次是从PREPARE语句)。变量本身是const,并且已经使用白名单获取了(从json请求解码时)。