Jump to content

Grouping rows by category


DrFishNips

Recommended Posts

I've never figured out how to do this. Lets say I have a database with fruits and vegetables in it. I want to display the contents of the DB but I need it to display them according to their category right now it just lumps them into the same category. For example I want to display the results like this:

 

Fruits:

Apples

Oranges

Mangos

 

Vegetables:

Carrots

Onions

Broccoli

 

right now I can only get it to display results like

Fruits

Apples

Oranges

Mangos

Carrots

Onions

Broccoli

 

So my problem is that all these entries are in the same DB table but I need to display them under different categories but I have no idea how. I've tried long and hard but can't figure it out so its time to get some help. Can anyone help me out with this?

 

Heres the code I'm using

$query = "SELECT * FROM food";

$result = mysql_query($query);



$num=mysql_num_rows($result);



$i=0;

while ($i < $num) {



$food = mysql_result($result,$i,"food");

$info = mysql_result($result,$i,"info");

$cat = mysql_result($result,$i,"cat");


echo "<h4>$food</h4>";
echo "<p>$info</p>";
++$i;



}

Link to comment
Share on other sites

Hi

 

Think you want something like this (with pretty minimal changes). If so really a php issue rather than a MySQL issue.

 

<?php
$query = "SELECT * FROM food ORDER BY cat";
$result = mysql_query($query);
$num=mysql_num_rows($result);
$i=0;
$prevCat = "";

while ($i < $num) 
{
$food = mysql_result($result,$i,"food");
$info = mysql_result($result,$i,"info");
$cat = mysql_result($result,$i,"cat");
if ($prevCat != $cat)
{
	echo "<b>$cat</b>";
	$prevCat = $cat;
}
echo "<h4>$food</h4>";
echo "<p>$info</p>";
++$i;
}
?>

 

Using more conventional MySQL reads of the database:-

 

<?php
$query = "SELECT * FROM food ORDER BY cat";
$result = mysql_query($query);
$prevCat = "";

while ($row = mysql_fetch_assoc($result))
{
$food = $row["food"];
$info = $row["info"];
$cat = $row["cat"];
if ($prevCat != $cat)
{
	echo "<b>$cat</b>";
	$prevCat = $cat;
}
echo "<h4>$food</h4>";
echo "<p>$info</p>";
}
?>

 

All the best

 

Keith

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.