我的数据库具有以下设置
productid | productname | category id
我想像这样输出它们:
category #1 item 1 item 2 item 3 category #2 item 1 item 2 item 3
我把它们组合在一起使用,并且工作正常,但我想循环遍历每个组并显示该组的内容.我该怎么做?
我建议只需要一个简单的查询来获取所有行,按类别ID排序.仅当其值从上一行更改时才输出该类别.
<?PHP
$stmt = $pdo-> query("SELECT * FROM `myTable` ORDER BY categoryID");
$current_cat = null;
while ($row = $stmt->fetch()) {
if ($row["categoryID"] != $current_cat) {
$current_cat = $row["categoryID"];
echo "Category #{$current_cat}\n";
}
echo $row["productName"] . "\n";
}
?>