View Single Post
Old 05-13-2009, 09:51 PM   #3 (permalink)
Wildhoney
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

Take the following as an example. Hopefully it should explain it well, and give you also a working example to build upon

php Code:
/* The original query with blanks to be filled in. */
$szSQL = "SELECT * FROM members ORDER by %s %s";

/* Set the defaults if invalid fields are supplied, or none at all. */
$szDefaultField = 'name';
$szDefaultOrder = 'asc';

/* Set the restrictions for both so users can't enter just anything. */
$aAllowedFields = array('name', 'username');
$aAllowedOrders = array('desc', 'asc');

/* Set to the ones specified, but if we have none, set to the defaults. */
$szField = isset($_GET['field']) ? strtolower($_GET['field']) : $szDefaultField;
$szOrderBy = isset($_GET['order']) ? strtolower($_GET['order']) : $szDefaultOrder;

/* Check if we're allowed this particular field in the query. */
if (!in_array($szField, $aAllowedFields))
{
    $szField = $szDefaultField;
}

/* Check if we're allowed this particular ordering in the query. */
if (!in_array($szOrderBy, $aAllowedOrders))
{
    $szOrderBy = $szDefaultOrder;
}

/* Build the new query with the ordering on field and ASC/DESC. */
$szSQL = sprintf($szSQL, $szField, $szOrderBy);

/* Query to execute... */
printf("Executing Query: %s", $szSQL);

Here is the form to be used in conjunction with this code:

html4strict Code:
<h1>Orders</h1>

<ul>
    <li><a href="?field=name&order=asc">Order by Name Ascending</a></li>
    <li><a href="?field=username&order=asc">Order by Username Ascending</a></li>
    <li><a href="?field=name&order=desc">Order by Name Descending</a></li>
    <li><a href="?field=username&order=desc">Order by Username Descending</a></li>
</ul>
Attached Files
File Type: php Order.php (1.4 KB, 95 views)
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote