Home >Database >Mysql Tutorial >How to Sort MySQL Data in an HTML Table Dynamically?

How to Sort MySQL Data in an HTML Table Dynamically?

Linda Hamilton
Linda HamiltonOriginal
2024-11-07 12:07:02281browse

How to Sort MySQL Data in an HTML Table Dynamically?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn