Home >Database >Mysql Tutorial >How to Sort HTML Table Rows Retrieved from MySQL?
In this scenario, we have an HTML table populated with data fetched from a MySQL database. The goal is to sort the table rows by clicking on the column headers (Type, Description, Recorded Date, Added Date).
To achieve this, we can leverage PHP and MySQL to handle the sorting logic.
The HTML table is structured as follows:
<table> <thead> <tr> <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> </tr> </thead> <tbody> <?php while($row = mysql_fetch_array($result)): ?> <tr> <td><?php echo $row['type']; ?></td> <td><?php echo $row['description']; ?></td> <td><?php echo $row['recorded_date']; ?></td> <td><?php echo $row['added_date']; ?></td> </tr> <?php endwhile; ?> </tbody> </table>
In the PHP code, we handle the sorting based on the $_GET['sort'] parameter.
<?php $sql = "SELECT * FROM MyTable"; if (isset($_GET['sort'])) { switch ($_GET['sort']) { case 'type': $sql .= " ORDER BY type"; break; case 'desc': $sql .= " ORDER BY description"; break; case 'recorded': $sql .= " ORDER BY recorded_date"; break; case 'added': $sql .= " ORDER BY added_date"; break; } } $result = mysql_query($sql); ?>
The SQL queries are modified dynamically to include the appropriate ORDER BY clause based on the user's selection.
It's crucial to note that user input should be sanitized before it's incorporated into an SQL query. This prevents malicious users from compromising the database. Sanitization involves validating and filtering user input to ensure it doesn't contain malicious characters or code.
The above is the detailed content of How to Sort HTML Table Rows Retrieved from MySQL?. For more information, please follow other related articles on the PHP Chinese website!