user265331 user265331 - 5 months ago 9
SQL Question

PHP & MYSQL: using group by for categories

My database has the following setup

productid | productname | category id


and I want to output them like so:

category #1
item 1
item 2
item 3

category #2
item 1
item 2
item 3


I used group by the group them together and that works fine, but I want to loop through each group and display the contents of that group. How would I do this?

Answer

I'd recommend just a simple query to fetch all the rows, sorted by category id. Output the category only if its value changes from the previous row.

<?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";
}

?>