为什么我的查询能处理3列,但不能处理4列或更多列


Why does my query work with 3 columns but fail with 4 or more?

此查询有效:

$con = mysql_connect("localhost","root","pw");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("db", $con);
$sql="INSERT INTO l1_clubmsg (msg, subject, status)
VALUES
(1,1,1)";
if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";
mysql_close($con);

但当我改变时:

$sql="INSERT INTO l1_clubmsg (msg, subject, status)
VALUES
(1,1,1)";

收件人:

$sql="INSERT INTO l1_clubmsg (msg, subject, status, to)
VALUES
(1,1,1,1)";

我得到这个错误:

Error: 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 'to) VALUES (1,1,1,1)' at line 1

l1_clubmsg 中不存在"to"列

你知道为什么会出错吗?感谢

TO是mysql中的一个保留字,因此如果您想将其用作列名,则需要像这样对其进行转义;

INSERT INTO l1_clubmsg (msg, subject, status, `to`) VALUES (1,1,1,1)

转义所有列和表名通常是个好主意,因为较新版本的数据库可能有新的保留字,但在这种情况下只需要一个。

不是因为有4列或更多列才产生错误。

产生错误的原因是to是一个关键字,不能像这样使用。

您可以将查询写成:

$sql="INSERT INTO l1_clubmsg (msg, subject, status, `to`)
VALUES
(1,1,1,1)";

对于关键字列表,你可以在这里查看

注意:通常在查询中尽量避免使用关键字。如果使用,请确保使用backticks(`)

对其进行转义

TO是MySQL中的一个保留字。您必须在查询中对其进行转义。尝试

$sql="INSERT INTO l1_clubmsg (msg, subject, status, `to`)
VALUES
(1,1,1,1)";

我添加的标点符号被称为反勾号。

我怀疑to是MySQL中的一项保留工作——您需要确保MySQL正确地解释为列名。代替:

INSERT INTO l1_clubmsg (msg, subject, status, to)
VALUES
(1,1,1,1)

尝试:

INSERT INTO l1_clubmsg (`msg`, `subject`, `status`, `to`)
VALUES
(1,1,1,1)

backticks确保对其进行了适当的解析。

您必须在TO周围加引号。