[英]PHP exception: SQLSTATE[42000]: Syntax error or access violation: 1064
I have a php pdo script where I want to select the record (from a table in a MySQL database) with the highest number in "field5". 我有一个php pdo脚本,我想在其中选择“ field5”中编号最高的记录(从MySQL数据库的表中)。 I also have a few other constrictions, see below:
我还有其他一些限制,请参见下文:
$stmt=$db->query("SELECT `field1`,`field2` FROM ".$tablename." WHERE
`field3`!=".$variable1." AND `field3`!=".$variable2." AND
`field4`='xx' AND `field5`<".$variable3." ORDER BY DESC `field5` LIMIT
1");
I have pretty much all the code inside a try-statement, and in the catch statement I use 我在try语句中包含了几乎所有代码,并且在catch语句中使用了
var_dump($ex->getMessage());
to get the exception message from the exception $ex. 从异常$ ex获取异常消息。
Now, when I execute the code I get the following exception message: 现在,当我执行代码时,我收到以下异常消息:
'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
'SQLSTATE [42000]:语法错误或访问冲突:1064您的SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DESC
field5
LIMIT 1' at line 3' (length=232)检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以便在“ DESC
field5
LIMIT 1”(第3行)(长度= 232)附近使用
I'd be grateful for any advice on what might be wrong! 对于可能出什么问题的任何建议,我将不胜感激!
Change 更改
ORDER BY DESC field5
into 进入
ORDER BY field5 DESC
Kindly refer the MySQL manual for the syntax of select query. 请参考MySQL手册 ,了解选择查询的语法。 You have made a simple mistake which is, the query was syntactically wrong .
您犯了一个简单的错误,即查询在语法上是错误的 。 You can only order the column by referencing it initially :
您只能通过首先引用该列来对其进行排序:
ORDER BY '{Column-Name}'
and then only you can define how it can be ordered either in ASC or DESC. 然后只有您可以定义如何在ASC或DESC中订购它。
ORDER BY '{Column-Name}' [ASC|DESC]
So you have to change the query as shown here : 因此,您必须更改查询,如下所示:
$stmt=$db->query("SELECT `field1`,`field2` FROM ".$tablename." WHERE
`field3`!=".$variable1." AND `field3`!=".$variable2." AND
`field4`='xx' AND `field5`<".$variable3." ORDER BY `field5` DESC
LIMIT 1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.