简体   繁体   English

向数据库中的值添加常量并使用PDO更新

[英]Adding constant to value in database and update with PDO

Here is the scenario: I need a mechanism to update a value (adding 1 to the current value) which is stored in a database for a certain user who logs in to the website. 这是场景:我需要一种机制来为某个登录到网站的用户更新存储在数据库中的值(将当前值加1)。 This is the current code: 这是当前代码:

$value = $row["value"];
$add_value = $db->prepare('UPDATE table SET value = $value + 1 WHERE email = :email');
$add_value->execute(array(':email'   => $email));

But what I receive is the following error message: Parse error: syntax error, unexpected T_LNUMBER in ... 但是我收到的是以下错误消息: 解析错误:语法错误,在...中意外T_LNUMBER

What am I doing wrong? 我究竟做错了什么?

First, you're using single quotes, that means that variables will not be parsed. 首先,您使用单引号,这意味着不会解析变量。 (The query is literally seeing $value and not the actual value). (查询从字面上看是$value而不是实际值)。

Second, you don't need to know the value in advance, the following works fine: 其次,您不需要事先知道该值,以下工作正常:

$add_value = $db->prepare('UPDATE `table` SET `value` = `value` + 1 WHERE `email` = :email');
$add_value->execute(array(':email'   => $email));

The database engine knows to update the field appropriately. 数据库引擎知道适当地更新该字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM