0
votes

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". 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

var_dump($ex->getMessage());

to get the exception message from the exception $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; 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)

I'd be grateful for any advice on what might be wrong!

2
Oh god, please use prepared statements if you're already using PDO... - naththedeveloper

2 Answers

0
votes

Change

ORDER BY DESC field5

into

ORDER BY field5 DESC
0
votes

Kindly refer the MySQL manual for the syntax of select query. 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.

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");