Great script! Just what I was looking for.
Thank you, thank you, thank you🙂
I have taken the liberty of rewriting it a bit so it will loop through the table titles and content. This way one does not have to manually write all the table title names. Its easier when you have big tables.
<?php echo "<a href=./>Home</a><br>";
// connect to db
$connect = mysqli_connect('localhost','user','pass','database');
// sets id as default sort (you can set something else than id)
$sort = (isset($_GET['sort'])) ? $_GET['sort'] : 'id';
// define sort order
$sort_order = 'asc';
if(isset($_GET['sort_by'])) {
if($_GET['sort_by'] == 'asc') {
$sort_order = 'desc';
} else {
$sort_order = 'asc';
}
}
// query table
$query = mysqli_query($connect,("SELECT * FROM table ORDER BY " . $sort . " " . $sort_order));
$keys = mysqli_fetch_array($query, MYSQLI_ASSOC);
// html table
echo "<table border='1'>";
// print out table columns
echo "<tr>";
foreach(array_keys($keys) as $key) {
switch($sort) {
case $key :
$order_by = $key;
break;
}
if($sort==$key) {
echo "<td bgcolor=lightgreen><a href='?sort=$key&sort_by=" . $sort_order . "'>$key</a></td>";
} else {
echo "<td bgcolor=lightblue><a href='?sort=$key&sort_by=" . $sort_order . "'>$key</a></td>";
}
}
echo "</tr>";
// print out table contents
$query = mysqli_query($connect,("SELECT * FROM table ORDER BY " . $sort . " " . $sort_order));
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
echo "<tr>";
foreach($row as $rows) {
echo "<td>" . $rows . "</td>";
}
echo "</tr>";
}
echo "</table>";
// close connection
mysqli_free_result($query);
mysqli_close($connect);
?>