View Full Version : Creating a sortable HTML table from a MySQL database

02-25-2009, 05:04 PM

I was wondering whether there is an easy way to create a sortable HTML table from data in a MySQL database. I get the data out of the DB using PHP. What I am talking about are those tables you often see around the web, where you can click on the headings and all of the data gets sorted by the heading that you clicked on. If you click again on the same heading, it will sort it in the other direction (ascending/descending).

Something with java or ajax would probably be best, but is there code that I can use to do this easily?



02-25-2009, 05:13 PM
Ajax and javascript aren't different languages. AJAX stands for Asynchronous JavaScript and XML so as you see its part of javascript. I'm guessing you don't want a page reload? If you didn't mind the page reload it would be simple. With a page reload all you would do is make the headers of the table links that have something like.

<a href="yourpage.php?order=columnname">Columnname</a>
Then just before your sql statement

$order = (isset($_GET['order'])) ? mysql_real_escape_string($_GET['order']) : 'defaultcolumnname';
$sql = "SELECT * FROM table ORDER BY $order ASC";
$result = mysql_query($sql) or die(mysql_error());
You get the idea. If you didn't want a page reload then look into this http://yoast.com/articles/sortable-table/

But I think you should still have the links for users with js disabled. Just add onclick="return false" so they don't go anywhere. With js disabled the page will reload with the correct order.

03-17-2009, 04:36 PM
Hi zachbb!

I strived the net for the same some weeks ago. Here is your ready-to-go solution: http://www.kryogenix.org/code/browser/sorttable/

Just download the js library and link it in your HTML head.

<script src="sorttable.js"></script>

Mark your table as a sortable one by giving it a class of "sortable":

<table class="sortable">

Note that the library's JavaScript file is called sorttable (two Ts), but the class you add to the table is sortable (one T).

Then you need a css file. I just created style.css

table.sortable thead {
font-weight: bold;
cursor: default;

And link it also in the HTML head:

<link rel="stylesheet" type="text/css" href="style.css">

Just read the link above or email me.


03-17-2009, 05:43 PM

That's great!

03-17-2009, 07:26 PM
Have you tried it yet? Does it work? I use Firefox only. For some reason it does not work in IE...

03-19-2009, 02:22 PM
This is what I use. It is very flexible and the instructions are detailed.

Table Sort Script (http://www.frequency-decoder.com/2006/09/16/unobtrusive-table-sort-script-revisited)