Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP & MYSQL: using group by for categories

Tags:

php

mysql

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?

like image 309
sam Avatar asked Jun 04 '10 19:06

sam


People also ask

What is PHP is used for?

PHP is an open-source server-side scripting language that many devs use for web development. It is also a general-purpose language that you can use to make lots of projects, including Graphical User Interfaces (GUIs).

Is PHP a coding?

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.

Is PHP coding or programming?

PHP is an open-source, server-side programming language that can be used to create websites, applications, customer relationship management systems and more. It is a widely-used general-purpose language that can be embedded into HTML.

Which is better Python or PHP?

Python is better than PHP in long term project. PHP has low learning curve, it is easy to get started with PHP. Compare to PHP Python has lower number of Frameworks. Popular ones are DJango, Flask.


4 Answers

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

?>
like image 131
Bill Karwin Avatar answered Oct 21 '22 13:10

Bill Karwin


This should work:

$categories = array();
$result= mysql_query("SELECT category_id, product_name  FROM `table` GROUP BY `catagory_id` ORDER BY `catagory_id`");
while($row = mysql_fetch_assoc($result)){
    $categories[$row['category_id']][] = $row['product_name'];
}

// any type of outout you like
foreach($categories as $key => $category){
    echo $key.'<br/>';
    foreach($category as $item){ 
        echo $item.'<br/>';
    }
}

The output you can style yourself. You simply add everything into a multidimensional array with the category id as the first level keys.

EDIT: The resulting array might look like this:

$categories = array(
    'cateogy_id_1' => array(
        1 => 'item_1',
        2 => 'item_2',
        ...
    ),
    'cateogy_id_2' => array(
        1 => 'item_1',
        2 => 'item_2',
        ...
    ),
    ....
);
like image 42
2ndkauboy Avatar answered Oct 21 '22 13:10

2ndkauboy


What you want is to order them by the category, not group them.

SELECT * FROM MyTable
ORDER BY category_id, product_id

When you iterate through the list, just output a new header whenever the category_id changes.

like image 35
Marcus Adams Avatar answered Oct 21 '22 14:10

Marcus Adams


This approach does not need the data to be sorted by category_id.

You can use php to group each category together in a nested array. After this, the data can be easily be displayed in a table, passed to a grap/chart library, etc...

<?php
$stmt = $pdo-> query("SELECT * FROM myTable ORDER BY categoryID");


$categories = []; //the array to hold the restructured data

//here we group the rows from different categories together
while ($row = $stmt->fetch())
{
    //i'm sure most of you will see that these two lines can be performed in one step
    $cat = $row["categoryID"]; //category id of current row
    $categories[$cat][] = $row; //push row into correct array
}

//and here we output the result
foreach($categories as $current_cat => $catgory_rows)
{
    echo "Category #{$current_cat}\n";

    foreach($catgory_rows as $row)
    {
        echo $row["productName"] . "\n";
    }
}
?>
like image 20
2MAS Avatar answered Oct 21 '22 12:10

2MAS