Home > Database > Mysql Tutorial > body text

How to Sort HTML Table Rows Dynamically from a MySQL Database?

Patricia Arquette
Release: 2024-11-07 00:39:03
Original
693 people have browsed it

How to Sort HTML Table Rows Dynamically from a MySQL Database?

How to Dynamically Sort HTML Table Rows Retrieved from a MySQL Database

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>
Copy after login

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;
}
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!