2016-08-23 49 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,而不是試圖重新實現輪。

相關問題