Print table with client-side sorting function

metalix 0 Tallied Votes 752 Views Share

To view this tutorial with notes at http://www.effectivewebdesign.co.nz/tutorial.php

yes I am aware this is more php than mysql. howerver I get asked how to do it so often I thought I'd post it here aswell :)

<?PHP
//connect info
$hostname = "localhost";
$database = "";
$username = "";
$password = "";
$conn = mysql_pconnect($hostname, $username, $password); 
$page = $_SERVER['PHP_SELF']; // Makes $page the current page e.g:query.php
//the query
if (!isset($sort)){
$sort = column1; // the one to sort by default
}
mysql_select_db($database, $conn);
$query = "SELECT * FROM table ORDER BY $sort";
$sql = mysql_query($query, $conn) or die(mysql_error());
//print the table
echo '<table><tr><td>column1</td><td>column2</td><td>column3</td></tr>';
while($row = mysql_fetch_assoc($sql)){
//echo the results
echo '<tr><td><a href="'.$page.'?sort=column1>"'.$row['column1'].'</a></td><td><a href="'.$page.'?sort=column2>"'.$row['column2'].'</a></td><td>a href="'.$page.'?sort=column3>"'.$row['column3'].'</a></td></tr>\n';
}
//close the table
echo '</table>';
?>