php - 如何修复 SQLSTATE[42000] 错误;使用准备好的语句

标签 php mysql mysql-error-1064

我正在尝试创建电子邮件确认脚本。

这是我的 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 方面的专家,但我在我的代码中找不到任何语法错误,我希望得到一些帮助。

最佳答案

根据 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 占位符或类似的占位符,但恰好绑定(bind)到相同的值,实际上是 MySQL 的 VALUES() ON DUPLICATE KEY UPDATE 子句中的函数采用列名而不是文字。因此,这将起到作用:

$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 ,而不是尝试重新实现轮子。

关于php - 如何修复 SQLSTATE[42000] 错误;使用准备好的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39107991/

相关文章:

PHP 关联数组 - 单引号与双引号

MYSQL:第一个表条目包含第二个表中的匹配条目。任何疑问想法

mysql - 我希望当没有选择过滤器时返回所有带有计数的数据

javascript - Vue 1 类绑定(bind)始终返回 false

php - PayPal IPN 总是返回 "INVALID"

php - CSS 和浏览器兼容性

mysql - 如何检查 MySQL 中的列是否为空或 null?

mysql - 使用 select 语句插入多行

MYSQL关于ROOT用户的安全问题

mysql - 创建过程mysql错误在 ''附近