Home >Database >Mysql Tutorial >How to Organize MySQL Data into Sections Using PHP's While Loop?

How to Organize MySQL Data into Sections Using PHP's While Loop?

Susan Sarandon
Susan SarandonOriginal
2024-12-24 20:09:10484browse

How to Organize MySQL Data into Sections Using PHP's While Loop?

How to Use a While Loop to Organize MySQL Data into Sections by a Given ID in PHP

In a MySQL table with columns for series_id, series_color, and product_name, you can display the data in organized sections by using a while loop in PHP. The desired output is given below:

A12 Series Product

 - Milk  
 - Tea 
 - sugar
 - water

B12 Series Product

 - Water 
 - Banana 
 - Cofee 
 - Tea

To achieve this, follow these steps:

  1. Order the Results:

    • Order the results by series_id to group the products with the same series ID together.
    $stmt = $pdo->prepare("SELECT series_id, product_name
                        FROM yourTable
                        ORDER BY series_id");
    $stmt->execute();
  2. Generate Sections:

    • Create a while loop that iterates through the results.
    • Initialize a variable $last_series to keep track of the previously displayed series ID.
    • Display the series header (
    • ) and start a new unordered list (
        ) when the series ID changes.
      $last_series = null;
      echo "<ul>\n";
      while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
          if ($row['series_id'] != $last_series) {
              if ($last_series) {
                  echo "</ul></li>\n";
              }
              echo "<li>" . $row['series_id'] . " Series Product\n";
              echo "<ul>\n";
              $last_series = $row['series_id'];
          }
          echo "<li>" . $row['product_name'] . "</li>\n";
      }
      if ($last_series) {
          echo "</ul></li>\n";
      }
      echo "</ul>\n";

The above is the detailed content of How to Organize MySQL Data into Sections Using PHP's While Loop?. 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