Home >Database >Mysql Tutorial >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:
Order the Results:
$stmt = $pdo->prepare("SELECT series_id, product_name FROM yourTable ORDER BY series_id"); $stmt->execute();
Generate Sections:
$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!