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?
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";
}
?>
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',
...
),
....
);
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.
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";
}
}
?>
The easiest way is probably to pull the list of categories, iterate through and pull their attached products. (I.e. several queries.)
For instance (pseudocode):
$result = fetch_assoc("SELECT category_id FROM categories"); foreach($result as $row) { echo $row['category_id']; $result2 = fetch_assoc("SELECT product_id FROM products"); foreach($result2 as $row2) { echo $row2['product_id']; } }
If you want to do it all in one query you can do something like:
$result = fetch_assoc("SELECT product_id, category_id FROM products p JOIN categories c ON p.category_id = c.category_id ORDER BY c.category_id ASC"); $last = null; foreach($result as $row) { # Output the category whenever it changes if($row['category_id'] != last) { echo $row['category_id']; $last = $row['category_id']; } echo $row['item_id']; }
Then you can iterate over the result set and pull out the category name whenever it changes.
There may be a more sophisticated, elegant way to write the SQL to do everything before you get it from the database, but I'm not that smart. ;)
Note: Examples use pseudo code. I use a mysql abstraction class that works like:
$db->query("SELECT stuff"); $db->multi_result(); // returns 2d-associative array
I can then foreach($db->multi_result() as $row)
, which is super lazy and awesome.
I can post the code for the abstraction layer if you like.
$stmt = $dbConnection->prepare("SELECT exam_id, COUNT(report_id) FROM bug_report GROUP BY exam_id; ");
//$stmt->bind_param('s',$exam_id);
$stmt->execute();
$extract = $stmt->get_result();
$count = $extract->num_rows;
if($count){
while($rows = $extract->fetch_assoc()){
$exam_id = $rows["exam_id"];
switch($exam_id){
case "jee_questions":
$jeeBugCount = $rows["COUNT(report_id)"];
break;
case "gate_questions":
$gateBugCount = $rows["COUNT(report_id)"];
break;
}
}
}
精彩评论