//get the messages from the database
$messagesID_query = mysql_query("SELECT
messageID,
posterID,
messageTime,
message
FROM
chat_messages
ORDER BY
messageTime DESC
LIMIT
20");
The above mysql_query returns the latest 20 entries from a table. However, I ideally need to reverse the resource before fetching the rows.
At the moment, I run 2 loops:
1 – one to fetch all the results in a php array
2 – then another to process the array to print once reversed.
I am trying to optimize the way this works… is it possible to reverse the mysql resource before i start fetching the rows so i do not have to reverse the array in php?
Or, is there a way that I have over looked of rewriting the query to return the said rows in reverse order.. but still getting the latest 20 results as the above does?
This is best done in the query. Wrap the whole thing in a subquery and reorder that back into ascending order by
messageTime. This could save considerable CPU resources on the database server over looping a bunch of calls tomysql_data_seek()to fetch rows backward on a larger rowset than your 20.