SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2006
    Posts
    87
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

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

  2. #2
    SitePoint Addict
    Join Date
    Aug 2013
    Location
    New Zealand
    Posts
    277
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    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

  3. #3
    SitePoint Evangelist ColinHughes's Avatar
    Join Date
    Sep 2004
    Location
    Spain
    Posts
    469
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you echo your query it looks like this:
    PHP Code:
    SELECT FROM items WHERE 1=1 ORDER BY id DESC AND size='' AND price='' 
    Try this:
    PHP Code:
    $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=AND size='' AND price='' ORDER BY id DESC 

  4. #4
    SitePoint Enthusiast
    Join Date
    May 2006
    Posts
    87
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Right you are ColinHughes! Your suggestion works perfectly. I am grateful to you for having made it. Thank you!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •