PHP & MYSQL: using group by for categories

前端 未结 6 713
栀梦
栀梦 2020-12-08 08:54

My database has the following setup

productid | productname | category id

and I want to output them like so:

category #1
it         


        
6条回答
  •  伪装坚强ぢ
    2020-12-08 09:56

    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.

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

提交回复
热议问题