How to let user change sort order?

Codes here !

Moderators: egami, macek, gesf

Post Reply
fredws
New php-forum User
New php-forum User
Posts: 14
Joined: Wed Jul 16, 2003 4:16 pm

Sun Aug 17, 2003 3:52 pm

Right now I have a page that pulls data from a table, like so:

// get client list
$query = "SELECT * from clients ORDER BY company";
$result = mysql_db_query($database, $query, $connection) or die ("Error in
query: $query. " . mysql_error());


//interate through resultset and display
while (list($clientid, $first_name,$last_name,$company,$address,$address2,$city,$state,$zip,$phone,$fax,$cell,$date_time)=mysql_fetch_row($result))
{
echo "<div class=\"content\"><b><center>$company</center></b><br />";
if ($first_name != '') echo "$first_name ";
if ($last_name != '') echo "$last_name<br />";
if ($address != '') echo"$address<br />";
if ($address2 != '') echo"$address2<br />";
if ($city != '') echo"$city";
if ($city != '' && $state != '') echo",";
if ($state != '') echo" $state";
if ($zip != '') echo" $zip<br />";
if ($phone != '') echo"Phone: $phone<br />";
if ($fax != '') echo"Fax: $fax<br />";
if ($cell != '') echo"Cell: $cell<br />";
$datentime = date('n/j/Y g:i a',strtotime($date_time));
echo "<br />Entry Date: $datentime";

echo "</div>";

}


I would like to have a link, or button that the user can click on and change which field the data is sorted by. What is the easiest way to do this?

TIA!
Joel
php-forum Super User
php-forum Super User
Posts: 193
Joined: Sat Mar 29, 2003 11:57 pm
Location: Auckland, New Zealand
Contact:

Sun Aug 17, 2003 4:16 pm

This is a pretty simple thing, note the difference in my querying way, mysql_db_query is outdated.

Code: Select all

//Check if order is set
if (isset($_GET['order'])) {
     if ($_GET['order'] === "company" ||
        $_GET['order'] === "first_name" ||
        $_GET['order'] === "last_name") {
                //If order set by user is valid
                $order = $_GET['order'];
     } else {
            $order = "company"; //Default Order
      }
} else {
    $order = "company"; //Default order
}


// get client list 
$query = "SELECT * from clients ORDER BY $order"; 
$result = mysql_query($query) or die ("Error in 
query: $query. " . mysql_error()); 

Then you can have these links

Code: Select all

<a href="<?php echo $_SERVER['PHP_SELF'] ?>?order=company">Order By Company</a>
<a href="<?php echo $_SERVER['PHP_SELF'] ?>?order=last_name">Order By Last Name</a>
Also, the usual way for doing things with data displaying, is by using arrays. This is an example. But if you like your way, stick with it, if you want. :D

Code: Select all

while ($row = mysql_fetch_assoc($result)) {
       echo $row['first_name'];
}
fredws
New php-forum User
New php-forum User
Posts: 14
Joined: Wed Jul 16, 2003 4:16 pm

Sun Aug 17, 2003 7:18 pm

That's what I was after!
Thanks Joel!
Post Reply