View Full Version : SQL syntax and sorting results
bluemicrobyte
08-10-2006, 7:53 PM
$query = "SELECT * FROM phpbb_ina_eventlog ORDER BY timestamp DESC LIMIT 10";
This gives me the latest 10 entries, with the newest being the first result. I'd like to take these 10 items and reverse them, so when I do
while ($row = mysql_fetch_array($result)) {
echo $row; //not the real code, just an example
}
the oldest item out of the 10 newest is first (and the newest at the bottom).
I've spent the past hour trying to get this done, and I must be missing a simple solution. Ideas?
edit: I've found a workaround, but I'd still like to know how to accomplish this sorting task for future reference :P
http://us3.php.net/function.mysql-data-seek
In Example 1 it shows how to fetch rows in reverse order.
Another option is save all the rows to a temporary array, and then read that array backwards.
There may be some easy way to do this in the MySQL query itself, but if so I don't know how.
bluemicrobyte
08-14-2006, 5:02 AM
Ah, that looks like it would do it, thanks Jeff. I didn't think to use mysql_data_seek like that :P
There's an even simpler solution built into SQL:
http://mysql.com/doc/refman/5.0/en/sorting-rows.html
The default sort order is ascending, with smallest values first. To sort in reverse (descending) order, add the DESC keyword to the name of the column you are sorting by:
mysql> SELECT name, birth FROM pet ORDER BY birth DESC;
DESC effects the direction of the ORDER BY. He wanted to reverse the order of the rows returned.
So for example if these are your rows:
id number
1 100
2 256
3 394
4 495
5 500
Let's say you want just the highest 3 numbers... but arranged from lowest to highest.
If you do this: SELECT id, number FROM numbers ORDER BY number DESC LIMIT 3
You will get:
5 500
4 495
3 394
But he wanted:
3 394
4 495
5 500
I don't know any easy way of doing that in MySQL. It's probably possible using temporary tables or something like that, but I think doing it in PHP is the better way to go.
But if he's just calling mysql_fetch_array, it shouldn't make a difference, right?
It matters if he wants it in reverse order, since mysql_fetch_array only goes in one direction :)
Markpyro
08-23-2006, 9:50 PM
Dude. I found this in like thirty seconds:
http://us2.php.net/array
array_reverse (http://us2.php.net/manual/en/function.array-reverse.php) -- Return an array with elements in reverse order
http://pyrom.net/sigs/manual/hr.png
http://pyrom.net/sigs/manual/sigimage.png
*http://pyrom.net/test/blamecountimage.php*http://pyrom.net/test/lastblameimage.php*
http://pyrom.net/test/blameclick.png (http://pyrom.net/test/blame.php)
A MySQL result isn't really an array. But like I said in my first post you could save the rows to a temporary array first.
vBulletin® v3.7.2, Copyright ©2000-2008, Jelsoft Enterprises Ltd.