2

I have a mysql table with these columns:

series_id, series_color, product_name

In the output I want to list the data in sections, with one section for each series_id, like this:

A12 Series Product

 - Milk  
 - Tea 
 - sugar
 - water

B12 Series Product

 - Water 
 - Banana 
 - Cofee 
 - Tea
ADyson
  • 57,178
  • 14
  • 51
  • 63
Erdal Bakkal
  • 343
  • 1
  • 6
  • 21

1 Answers1

3

Order your results by series_id, so all the products with the same value will be together.

$stmt = $pdo->prepare("SELECT series_id, product_name
                       FROM yourTable
                       ORDER BY series_id");
$stmt->execute();

Then when displaying the results, show the Series header and start a new <ul> whenever it 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 "</li>\n";
}
echo "</ul>\n";
Barmar
  • 741,623
  • 53
  • 500
  • 612