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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-07 00:39:03694browse

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>

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!

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