How to let user change sort order?

A

Anonymous

Guest
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!
 
This is a pretty simple thing, note the difference in my querying way, mysql_db_query is outdated.
Code:
//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:
<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:
while ($row = mysql_fetch_assoc($result)) {
       echo $row['first_name'];
}
 
Back
Top