2011-11-27 70 views
3

我已阅读此主题:Issues incrementing a field in MySQL/PHP with prepared statements但未看到我的问题的答案。使用PDO准备好的声明并递增列值

PDOStatement Object 
(

    [queryString] => UPDATE user_alerts SET notif = ? + 2 WHERE (user_id = ?) 

) 

$stmt->execute(array('notif', '1')); 

据我所知,这一切都是正确的。

当上面的代码执行时,它将notif列设置为等于2,而不管notif列的值是什么。就好像SQL读取像SET notif = 2而不是SET notif = notif + 2

我一直没能弄明白,真的很感激帮助!

回答

3
$sql = 'UPDATE user_alerts SET notif = notif + 2 WHERE (user_id = :userid)'; 
$prepStatement = $pdo->prepare($sql); 
$prepStatement->execute(array(':userid' => $userid)); 

不能列名绑定到一个事先准备好的声明。

6

使用参数不仅仅是一个简单的文本替换。您不能用参数替换列名称。因为如果你写了MySQL将解释你的查询这样的:

UPDATE user_alerts SET notif = 'notif' + 2 WHERE (user_id = ?) 

字符串'notif'被转换成零加成。

试试这个查询,而不是:

UPDATE user_alerts SET notif = notif + 2 WHERE (user_id = ?)