简体   繁体   English

故障排除 PHP MySQL 查询

[英]Troubleshoot PHP MySQL Query

I am trying to run this query:我正在尝试运行此查询:

$q1 = "INSERT INTO `Validation` (`Key`, `Status`, `Notes`, `Serial`) VALUES (max(Key)+1, 'Valid', '".mysql_real_escape_string($user)."', '0')";

through my PHP script, but each time it displays this error:通过我的 PHP 脚本,但每次都显示此错误:

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 'Key)+1, 'Valid', 'USER', '0')' at line 1

Any ideas?有任何想法吗?

KEY is a MySQL reserved word , so if you've picked it as a column name, you must quote it (with backticks) every time: KEY是一个MySQL 保留字,所以如果你选择它作为列名,你必须每次都引用它(带反引号):

$q1 = "INSERT INTO `Validation` (`Key`, `Status`, `Notes`, `Serial`) 
    VALUES (
        max(`Key`) + 1, 
        'Valid', 
        '".mysql_real_escape_string($user)."'
        , '0'
    )";

Note that you don't have to quote non-reserved words with backticks.请注意,您不必用反引号引用非保留词。

I'm not actually sure that this will work -- doesn't MySQL prohibit reading from the same table that you're updating in a single query still?我实际上不确定这是否可行——MySQL 是否仍然禁止从您在单个查询中更新的同一个表中读取? Regardless, as mentioned in the comments, it looks like you're just replicating by hand what AUTO_INCREMENT does for you automatically.无论如何,正如评论中提到的,您似乎只是在手动复制AUTO_INCREMENT自动为您所做的事情。 Consider using it instead.考虑改用它。

I'm not sure you can use Key there.我不确定你可以在那里使用 Key。 One way round this would be to do a SELECT statement before the INSERT to find out the max(Key) value.解决此问题的一种方法是在 INSERT 之前执行 SELECT 语句以找出最大(键)值。 Another (preferable) way would be to make the database auto increment the KEY column另一种(首选)方法是使数据库自动增加 KEY 列

Try using a subquery.尝试使用子查询。

$q1 = "INSERT INTO `Validation` (`Key`, `Status`, `Notes`, `Serial`) VALUES ((SELECT max(Key) FROM Validation)+1, 'Valid', '".mysql_real_escape_string($user)."', '0')";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM