PDA

View Full Version : Ranking Alphabetically


losse
06-29-06, 11:25 AM
Hi there
Right now I have page where I list all the users on my site... They are just ranked according to the order they entered the DB...

I would like to allow a ranking feature where you click on the column (say, "name", or "last name") and it automatically ranks the results...

Is that possible with PHP?

This is the script I have right now that spits out the users in my DB

while ($client = mysql_fetch_array($clients)) {
$id = $client['id'];
$name = htmlspecialchars($client['name']);
$last = htmlspecialchars($client['last']);
echo "<li>$name ". "$last ".
"<a href='cms_editclient.php?id=$id'>Edit</a> ".
"<a href='deleteclient.php?id=$id'>Delete</a></li>";

Your help is greatly appreciated.

Nico
06-29-06, 11:33 AM
Moved to database.

And yes, it's possible.



$allowed_orders = array('name', 'last', 'id'); // Etc..
$order = in_array($_GET['order'], $allowed_orders) ? $_GET['order'] : 'id';

$query = "SELECT * FROM clients ORDER BY ". $order;




<a href="clients.php?order=name">Order by name</a>
<a href="clients.php?order=last">Order by last name</a>


Something like this should do it.

losse
06-29-06, 11:45 AM
Thanks Nico

Are there any IF / ELSE statements I should be worried about? This is the entire script I'd be putting it...

<?php

$dbcnx = @mysql_connect('xxx', 'xxx', 'xxx');
if (!$dbcnx) {
exit('<p>Unable to connect to the ' .
'database server at this time.</p>');
}

if (!@mysql_select_db('xxx')) {
exit('<p>Unable to connext</p>');
}

$clients = @mysql_query('SELECT id, name, last FROM client');
if (!$clients) {
exit('<p>Error retrieving authors from database!<br />'.
'Error: ' . mysql_error() . '</p>');
}

while ($client = mysql_fetch_array($clients)) {
$id = $client['id'];
$name = htmlspecialchars($client['name']);
$last = htmlspecialchars($client['last']);
echo "<li>$name ". "$last ".
"<a href='cms_editclient.php?id=$id'>Edit</a> ".
"<a href='deleteclient.php?id=$id'>Delete</a></li>";
}

?>

And where would this code go?

<a href="clients.php?order=name">Order by name</a>
<a href="clients.php?order=last">Order by last name</a>

Nico
06-29-06, 11:48 AM
Add the code before executing the main query, and add "ORDER BY $order" to it.


$allowed_orders = array('name', 'last', 'id'); // Etc..
$order = in_array($_GET['order'], $allowed_orders) ? $_GET['order'] : 'id';

$clients = @mysql_query('SELECT id, name, last FROM client ORDER BY '. $order);


This should work.

EDIT:

And the links would go anywhere on your page where you want to be able to change the order.

losse
06-29-06, 11:54 AM
thanks man!

and clients.php is basically the name of the file where all that php code is on right? It's not a new php page?

Nico
06-29-06, 11:59 AM
Yeh, it's the same page. I just called it like that cause I didn't know how your was called.