"ORDER BY id DESC" not working with "WHERE 1=1"

Gracious, I must be doing something silly. I’m trying to order the results of an admittedly complicated query, but when I add “ORDER BY id DESC” it fails. Here’s the code:

$query=“SELECT * FROM items WHERE 1=1 ORDER BY id DESC”;
if ($size != ‘’)
$query .= " AND size=‘$size’“;
if ($price!= ‘’)
$query .= " AND price=‘$price’”;

If I leave out “ORDER BY id DESC” it works, but lists the results in ascending id order. I want them in descending id order. Please, can someone help me spot the error that I must obviously be making? Thank you!:slight_smile:

Usually the “order by …” clause needs to be last but you’re appending to the end of it.

Sent from my XT316 using Tapatalk 2

If you echo your query it looks like this:

SELECT * FROM items WHERE 1=1 ORDER BY id DESC AND size='' AND price=''

Try this:

$query="SELECT * FROM items WHERE 1=1";
if ($size != '')
$query .= " AND size='$size'";
if ($price!= '')
$query .= " AND price='$price'";
$query .= " ORDER BY id DESC";

// Produces

SELECT * FROM items WHERE 1=1 AND size='' AND price='' ORDER BY id DESC


Right you are ColinHughes! Your suggestion works perfectly. I am grateful to you for having made it. Thank you!