Sorting Rows in an HTML Table Retrieved from MySQL
When dealing with data tables obtained from MySQL, sorting the rows interactively becomes essential. Here's how you can achieve this using a simple approach:
Dynamic Sorting Using Links
To sort the rows, you need to implement links on the column headers that retrieve the data from the same page. By incorporating a query string variable in the links, you can identify which column was clicked.
For instance, your HTML for the table headers could be:
<th><a href="mypage.php?sort=type">Type:</a></th> <th><a href="mypage.php?sort=desc">Description:</a></th> <th><a href="mypage.php?sort=recorded">Recorded Date:</a></th> <th><a href="mypage.php?sort=added">Added Date:</a></th>
Ordering via SQL Query
In your PHP code, you can then use the $_GET variable to determine which column to sort by. Here's an example:
$sql = "SELECT * FROM MyTable"; if ($_GET['sort'] == 'type') { $sql .= " ORDER BY type"; } elseif ($_GET['sort'] == 'desc') { $sql .= " ORDER BY Description"; } elseif ($_GET['sort'] == 'recorded') { $sql .= " ORDER BY DateRecorded"; } elseif($_GET['sort'] == 'added') { $sql .= " ORDER BY DateAdded"; }
By incorporating this method, you can add interactivity to your tables, making it easy for users to sort data based on their needs.
The above is the detailed content of How to Sort MySQL Data in an HTML Table Dynamically?. For more information, please follow other related articles on the PHP Chinese website!