List MySQL results in different order?

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
tomsace
Forum Contributor
Posts: 167
Joined: Thu Jan 01, 2009 8:07 pm

List MySQL results in different order?

Post by tomsace »

Hey,
I have searched the net but I don't know what to search for? I have listed my list of games on my games website in order of newest first, how would I go about adding a drop down menu to allow the user to re-order the list in different ways e.g.
Newest first,
Oldest first etc...
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Re: List MySQL results in different order?

Post by jayshields »

Just have a form which when submitted executes a query which fetches the same results but with a different ORDER BY clause?
Yossarian
Forum Contributor
Posts: 101
Joined: Fri Jun 30, 2006 4:43 am

Re: List MySQL results in different order?

Post by Yossarian »

page one.php contains 2 links:

Code: Select all

 
<a href="list-games.php?date_order=desc">Newest</a>
<a href="list-games.php?date_order=asc">Oldest</a>
 
page list-games.php does this:

Code: Select all

 
<?php
$order = $_GET['date_order'] ;
 
if( !in_array( $order, array( 'desc', 'asc' ) ) {
// send away - out of range of the provided "white list"
die();
}
 
$sql = "select name from games order by production_date " . $order ;
 
// send that sql into your database and show results.
 
?>
 
So, filter incoming variables against a white list, and "build up" an sql query.

Its possible to "build up" an sql query with other variables, like LIMIT and WHERE clauses too.

It can get very messy if you have too many, and you should investigate other methods of doing this once it gets too complicated (eg using OOP).

HTH
Post Reply