Jump to content

ascending order


vang163

Recommended Posts

hi,

i've a table 'user' [name, address, phone].

 

eg. i've echo all the user details in a html file in a table format as below:

name  address | phone

---------------------------

john    |  USA    | 1234567

mary  |  JP        | 5678901

 

Now, i want to re-arrange the data in the table.

When i click on the column field 'name', the data will be re-arrange in asc order. When i click again on the 'name', the data will be re-arrange in desc order. This behaviour is the same for colume 'address' and column 'phone'.

can someone show me the technique to achieve this?

Link to comment
https://forums.phpfreaks.com/topic/116240-ascending-order/
Share on other sites

this code should work. I made it dirty, so you can figure out how to improve it (and because I'm lazy at times)

<?php
$allowed_order = array("name", "address", "phone");
if (isset($_GET['order']) && in_array($_GET['order'], $allowed_order)){
$order_by = $_GET['order'];
}
else{
$order_by = "name";
}
$allowed_dir = array("asc", "dec");
if (isset($_GET['order_dir']) && in_array($_GET['order_dir'], $allowed_dir)){
$order_dir = strtoupper($_GET['order_dir']);
}
else{
$order_dir = "DESC";
}
$sql = "SELECT * FROM `user` ORDER BY `$order_by` $order_dir;";
$result = mysql_query($sql);
if ($order_dir == "DESC" && $order_by == "name"){
$name_addr = "?order=name&order_dir=asc";
$address_addr = "?order=address&order_dir=desc";
$phone_addr = "?order=phone&order_dir=desc";
}
elseif ($order_dir == "DESC" && $order_by == "address"){
$name_addr = "?order=name&order_dir=desc";
$address_addr = "?order=address&order_dir=asc";
$phone_addr = "?order=phone&order_dir=desc";
}
elseif ($order_dir == "DESC" && $order_by == "phone"){
$name_addr = "?order=name&order_dir=desc";
$address_addr = "?order=address&order_dir=desc";
$phone_addr = "?order=phone&order_dir=asc";
}
else{
$name_addr = "?order=name&order_dir=desc";
$address_addr = "?order=address&order_dir=desc";
$phone_addr = "?order=phone&order_dir=desc";
}
print "<center><table border='1'><tr><td><strong><a href='$name_addr'>Name</a></strong></td><td><strong><a href='$address_addr'>Address</strong></td><td><strong><a href='$phone_addr'>Phone</a></strong></td></tr>\n";
while ($row = mysql_fetch_assoc($result)){
$name = $row['name'];
$address = $row['address'];
$phone = $row['phone'];
print "<tr><td>$name</td><td>$address</td><td>$phone</td></tr>\n";
}
print "</table></center>";

Link to comment
https://forums.phpfreaks.com/topic/116240-ascending-order/#findComment-597855
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.