pdo准备好的声明不起作用

Kel*_*sen 0 php mysql syntax pdo

我正在从mysql_connect切换到pdo,但无法实现.这是我的代码:

//get the row sk
$sk = strtok($string, "_");
//get the column name (the rest of the $string)
$column_name = substr($string, strpos($string, "_") + 1);
//get the value
$value = $_SESSION['save_arr'][$string];
echo "{$column_name} {$value} {$sk}</br>";
$sql = "update tbl_brand set ?=? where brand_sk=?";
$q = $pdo_conn->prepare($sql);
$q->execute(array($column_name, $value, $sk));
Run Code Online (Sandbox Code Playgroud)

如果我硬编码一些值,那么它工作正常

$sql = "update tbl_brand set name_long='name' where brand_sk='1'";
Run Code Online (Sandbox Code Playgroud)

我确定这只是一个语法问题,但我无法看到它.我正在研究这个例子http://www.phpeveryday.com/articles/PDO-Error-Handling-P552.html

回声的结果如下:

name_long National Autjho Glass 2

jsp*_*cal 7

列名不能绑定到预准备语句中的动态值.只能绑定字符串和整数等常量.所以,你的sql在准备之前应该包含列名:

$sql = "update tbl_brand set `$column` = ? where brand_sk = ?";
Run Code Online (Sandbox Code Playgroud)

在将它嵌入sql语句之前,你需要确保正确清理$ column值.

在mysql中,您可以像这样转义列标识符:

$column = str_replace("`", "``", $column);
Run Code Online (Sandbox Code Playgroud)