How to list data in a section by ID using while loop in PHP?
P粉505917590
P粉505917590 2023-11-17 20:03:03
0
1
1040

I have a mysql table with these columns:

series_id, series_color, product_name

In the output, I want to list the data by sections, one section per series_id like this:

A12 Series Product

 - Milk  
 - Tea 
 - sugar
 - water

B12 Series Product

 - Water 
 - Banana 
 - Cofee 
 - Tea


P粉505917590
P粉505917590

reply all(1)
P粉085689707

Sort the results by series_id so all 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, display the series title and start a new one if 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";
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!