SQL 插入查询中的语法错误

SQL Syntax error in insert query

大家好,我在插入查询时遇到错误 下面是查询

回声$sql="INSERT INTO event(mode,title,desc,date,status)VALUES('$mode','$title','$desc','$date','$status')";

以下为错误

您的 SQL 语法错误

查看与您的 MySQL 服务器版本相对应的手册,了解在 'desc,date,status)VALUES('Event','fdsagsd','fa sdgavsd ','2015-01-21','1')' at line 1

附近使用的正确语法

描述被误解了*。您需要使用 `` 对其进行转义,或者为描述之类的列使用更好的名称(最好是后者或两者)。

INSERT INTO event(mode,title,`desc`,date,status)VALUES('Event','fdsagsd','fa sdgavsd ','2015-01-21','1');
  • Desc 也用在 SELECT 查询中,以按指定列降序排列结果。

问题是 desc 是一个保留字(想想 order by),所以当您将它用作列名时,您需要用反引号对它进行引号。

来自section 9.2 of the MySQL documentation

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers. This section describes the permissible syntax for identifiers in MySQL. Section 9.2.2, “Identifier Case Sensitivity”, describes which types of identifiers are case sensitive and under what conditions.

An identifier may be quoted or unquoted. If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick (“`”):

mysql> SELECT * FROM `select` WHERE `select`.id > 100;

所以你想要的SQL是:

INSERT INTO event(mode, title, `desc`, date, status)
VALUES ('Event', 'fdsagsd', 'fa sdgavsd ', '2015-01-21','1')

(额外的空格不是 必需的 当然,但我建议包括它们只是为了使 SQL 更具可读性。)

当然,鉴于您需要在所有使用列名的地方引用它,您可能会决定将其重命名为 而不是 会更简单保留字 - 这在一定程度上取决于其他代码已经使用该架构的程度。

由于 date 和 desc 是键,因此在每个字段前后添加反引号 (`)。