How to order a set of results without re-querying the DB?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mcccy005
Forum Contributor
Posts: 123
Joined: Sun May 28, 2006 7:08 pm

How to order a set of results without re-querying the DB?

Post by mcccy005 »

I originally was asking questions about reversenatcase; but then silly me realised I could give myself the option of using the 'ORDER BY' capabilities of MySQL. (Don't worry though - I still need to reverse natcase thingy.)

What I want to do is parse a result from an sql query to a function.
Once I have $result; is there a way I can re-order this result?

OR would I be better off at re-querying the database using a new 'sort by' for when I want to sort by a different column of a table?? What I'm thinking is would (or COULD) a result end up being an extremely large object to parse around if I got hundreds of results in each query?
Would it rather be more efficient/'better programming' for me to re-query the database using a new 'order by'?

Thanks.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

In short: No, you cannot sort a result source.

But, you can iterate the results into an array, then order the array as you see fit.
mcccy005
Forum Contributor
Posts: 123
Joined: Sun May 28, 2006 7:08 pm

Post by mcccy005 »

Yeah thanks - the more I think about it though, the stupider it would be to put the results into an array.
I'm thinking I'll just modify the sql query on the fly with the 'LIMIT', 'ORDER BY' and 'ASC/DESC' functions of MySQL and maintain a record of the current results being displayed and maximum results per page.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

If you're paginating the result a new query is the way to go. If not and the sort order is based on user interaction you could either reload the page with the new query or potentially use javascript to sort the results. Where possible I would tend to go the javascript route with the backup of page reload to reduce server processing and traffic.
Post Reply