views:

48

answers:

2

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 ");
+4  A: 

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.

Matt
I think that's optional it should work w/o backticks too
Salil
@Salil - backticks are optional, but not when your column shares its name with a language keyword.
Matt
yes i agree w/o but it's not mention earlier.
Salil
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 :)
Wrikken
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') $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>
+4  A: 

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`

Hammerite