Home >Database >Mysql Tutorial >How to Sort HTML Table Rows Retrieved from MySQL?

How to Sort HTML Table Rows Retrieved from MySQL?

Susan Sarandon
Susan SarandonOriginal
2024-11-07 00:02:02980browse

How to Sort HTML Table Rows Retrieved from MySQL?

Sorting 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.

HTML Structure

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>

PHP Logic

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);

?>

MySQL Queries

The SQL queries are modified dynamically to include the appropriate ORDER BY clause based on the user's selection.

Security Considerations

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!

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