2016-08-23 98 views
0

我正在尝试创建一个电子邮件确认脚本。如何修复SQLSTATE [42000]错误;使用预准备语句

这是我的PHP代码:

... 
$q = $dbh->prepare("INSERT INTO `email_confirm` (UserID,token,tokenDate) VALUES(:id, :token, UTC_TIMESTAMP()) ON DUPLICATE KEY UPDATE token = VALUES(:token), tokenDate = UTC_TIMESTAMP();"); 
$result = $q -> execute(array(":id" => $this->id, ":token" => $token)); 
... 

在运行此,我收到以下错误:

Caught exception: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?), tokenDate = UTC_TIMESTAMP()' at line 1 

我在MySQL的专家,但我找不到任何语法在我的代码中出现错误,我很乐意提供一些帮助。

+1

'values()'函数不需要拥有自己的占位符或重复的占位符。只需使用您最初提供值的字段的名称:在重复键集foo = values(foo)'上插入...(foo,...)values($ foo,...)。 mysql会查看'values($ foo,....)'部分并提取在那里提供的值。 –

回答

4

由于PDO::prepare下记载:

You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute() . You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.

虽然你可以添加一个:token2占位符或类似恰好被绑定到相同的值,实际上MySQL的的ON DUPLICATE KEY UPDATE子句中VALUES()功能采用列名不是字面。因此,这将这样的伎俩:

$q = $dbh->prepare(' 
    INSERT INTO email_confirm 
    (UserID, token, tokenDate) 
    VALUES 
    (:id, :token, UTC_TIMESTAMP()) 
    ON DUPLICATE KEY UPDATE 
    token = VALUES(token), 
    tokenDate = UTC_TIMESTAMP() 
'); 

但是,您可能想看看Automatic Initialization and Updating for TIMESTAMP and DATETIME,而不是试图重新实现轮。

相关问题