How to reverse a MySQL result set?

I 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";
}
Tags: 

Comments

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.