SQLSTATE[42000]:语法错误或访问冲突:1064 你的 SQL 语法有错误 — PHP — PDO

问题描述:

我已经浏览了所有其他 StackOverflow(和谷歌)帖子,但都没有解决我的问题.

I've looked through all the other StackOverflow (and google) posts with the same problem, but none seemed to address my problem.

我正在使用 PDO 和 PHP.

I am using PDO and PHP.

我的代码:

$vals = array(
   ':from'    => $email,
   ':to'      => $recipient,
   ':name'    => $name,
   ':subject' => $subject,
   ':message' = >$message
);
print_r($vals);
try {
   $pdo = new PDOConfig();
   $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   $sql = "SELECT * FROM messages WHERE `message` LIKE :message";
   $q = $pdo->prepare($sql);
   $q->execute(array(':message' => $vals[':message']));
   $resp = $q->fetchAll();

   foreach ($resp as $row) {
      throw new Exception('Please do not post the same message twice!');
   }

   $sql = "INSERT INTO messages (from, to, name, subject, message) VALUES (:from, :to, :name, :subject, :message)";
   $q = $pdo->prepare($sql);
   $q->execute($vals);
} 
catch(PDOException $e) {
   echo $e->getMessage();
}

第一个print_r给出

and the first print_r gives

Array ( [:from]    => abc@gmail.com 
        [:to]      => lala@me.com 
        [:name]    => abc 
        [:subject] => abc 
        [:message] => abc )

这是预期的(没有一个是空的)

which is expected (none are null)

但它输出错误

SQLSTATE[42000]:语法错误或访问冲突:1064 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在从、到、名称、主题、消息"附近使用的正确语法(abc@gmail.com"、lala@me.com"在第 1 行>

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 'from, to, name, subject, message) VALUES ('abc@gmail.com', 'lala@me.com' at line 1

不知道如何解决这个问题.有什么想法吗?

No idea how to fix this. any ideas?

from 是 SQL 中的关键字.您不能在不引用它的情况下将其用作列名.在 MySQL 中,诸如列名之类的内容使用反引号引用,即 `from`.

from is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`.

就我个人而言,我不会打扰;我只是重命名该列.

Personally, I wouldn't bother; I'd just rename the column.

附注.正如评论中指出的那样, to 是另一个 SQL 关键字,因此也需要引用它.方便的是,drupal.org 上的人维护了一个 列表SQL 中的保留字.

PS. as pointed out in the comments, to is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.