1

I am calling the results form a query to a list on my site based on if the item is "downtown_hosted". This works fine but I would now like to sort that list DESC, but can't seem to get the syntax correct.

Below is what I have:

$result_events = mysql_query("SELECT * FROM events 
                                WHERE downtown='downtown_hosted'
                                ORDER BY date DESC
                                LIMIT 5 ");
2
  • 1
    And the error/what goes wrong? Commented Jun 16, 2010 at 15:53
  • The issue is that events don't display when I have the "ORDER BY date DESC LIMIT 5" in select from. If I remove this call the items display but out of the desired DESC order. Commented Jun 17, 2010 at 21:13

2 Answers 2

6

You need to escape the word "date" with backticks.

E.g.:

$result_events = mysql_query("
    SELECT * FROM events
    WHERE downtown='downtown_hosted'
    ORDER BY `date` DESC
    LIMIT 5
");

In practice it's not a bad habit to get into always enclosing your columns with backticks, so you will not have to worry about conflicting with language keywords.

Sign up to request clarification or add additional context in comments.

3 Comments

@Salil - backticks are optional, but not when your column shares its name with a language keyword.
In practice it's not a bad habit to try to use ANSI SQL as much as possible and to avoid keywords as column names :)
If I remove the "ORDER BY date DESC LIMIT 5" the items will display in the list but they are out of order. So the issue maybe with my list. The code I have for my list is: <? $i = 0; while($row = mysql_fetch_assoc($result_events)) { if(strtotime($row['end_date']) > date('U') && $i < 6) { $i++; $title = $row['title']; $id = $row['id']; ?> <table> <tr> <td align="center" <? if($i % 2){ ?> bgcolor="#DAE8F7"<? } ?>><span class=" newsLINK"><a href="events.php#<?=$id?>"><?=$title?></a></span></td> </tr> <? } } ?> </table>
6

date is an SQL keyword. You can have a column called date, but every time you refer to it you will have to use identifier quotes. In MySQL this is accomplished using backticks: `date`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.