Home > Database > Mysql Tutorial > body text

How to Sort HTML Table Rows Retrieved from MySQL Database on Click?

Susan Sarandon
Release: 2024-11-07 22:04:03
Original
636 people have browsed it

How to Sort HTML Table Rows Retrieved from MySQL Database on Click?

Sorting Rows of an HTML Table Populated from MySQL

To sort the rows of an HTML table retrieved from a MySQL database onClick by its headers, follow these steps:

HTML Markup:

  • Convert column headers to hyperlinks within elements, each linking to the same page with a query string parameter named 'sort' and its corresponding value indicating the sorting column.
<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>
Copy after login

PHP Code:

  • In the PHP code that generates the table rows:

    • Use the 'sort' parameter from the GET request to modify the SQL query with the appropriate ORDER BY clause.
$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";
}
Copy after login

Caution:

  • Remember to sanitize user input before including it in your SQL query to prevent malicious SQL injections.

The above is the detailed content of How to Sort HTML Table Rows Retrieved from MySQL Database on Click?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template