Introduction
Sorting table rows based on column values is essential for organizing and filtering data. This article will provide a comprehensive guide on how to sort rows in an HTML table populated from a MySQL database.
Creating Dynamic Sorting Links
To enable sorting, create links on the column headers that point to the same page. Include a query string variable to specify the sort criterion, such as "sort=type" for sorting by type.
<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>
Handling Sorting in PHP
In your PHP code, use the $_GET['sort'] variable to modify the MySQL query accordingly.
<?php $sql = "SELECT * FROM MyTable"; switch ($_GET['sort']) { case 'type': $sql .= " ORDER BY type"; break; case 'desc': $sql .= " ORDER BY Description"; break; case 'recorded': $sql .= " ORDER BY DateRecorded"; break; case 'added': $sql .= " ORDER BY DateAdded"; break; }
Security Considerations
Protect against SQL injection by validating the $_GET['sort'] value to prevent malicious input from modifying the query.
The above is the detailed content of How to Sort HTML Table Rows Dynamically from a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!