pdo准备好的声明不起作用

时间:2012-10-22 00:31:45

标签: 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));

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

$sql = "update tbl_brand set name_long='name' where brand_sk='1'";

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

回声的结果如下:

name_long National Autjho Glass 2

1 个答案:

答案 0 :(得分:7)

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

$sql = "update tbl_brand set `$column` = ? where brand_sk = ?";

在将其嵌入sql语句之前,您需要确保正确清理$ column值。

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

$column = str_replace("`", "``", $column);