How to reverse a MySQL result set?
Posted by admin | Under PHP, SQL Friday Jun 10, 2011I need to grab last 100 rows of a MySQL table, and loop them through in reverse order. The array_reverse() PHP function won’t reverse the “resource” or “array” data types, so it isn’t as easy to reverse the array of “mixed” data type. The best way to achieve this is by using a SQL statement as shown below.
SELECT * FROM (SELECT * FROM mytable ORDER BY id DESC limit 100) AS foo ORDER BY id ASC;
You may also retrieve the MySQL result set in descending order, and traverse the set in reverse order.
/* fetch MySQL result set in reverse order */
for ($i = mysql_num_rows($resultset) – 1; $i >= 0; $i–) {
mysql_data_seek($resultset, $i);
$row = mysql_fetch_assoc($result);
echo $row['abc'] . ‘ ‘ . $row['xyz'] . “\n”;
}









