Jump to content

Grouping my returned database results


Schlo_50

Recommended Posts

What im trying to do: I have been echo'ing out database results and ordering them into a price list.

E.g.

 

Category

Product

Product

Category

Product

Product

Product

Product

 

Problem: The results are echo'ed out in the order above but my code will only do the above if the categories are ordered from within the database. What i mean is, if in my database i add 4 items and don't order them by category upon input of the data as below:

 

|CategoryId | Item  |

|  Cat1      | Item1 |

|  Cat1      | Item2 |

|  Cat2      | Item3 |

|  Cat1      | Item4 |

 

I end up with

 

Cat1

item1

item2

Cat2

Item3

Cat1

Item4

 

I want my code to group all the items under their correct category name:

 

Cat1

Item1

Item2

Item4

Cat2

Item3

 

My code:

 

<?php
include('odbc.php');
$sql = odbc_exec("select * from Product1");

$prevCat='';
while($row = odbc_fetch_array($sql))
{
$title = $row["titlefield"];
$id = $row["idfield"];
$price = $row["pricefield"];
$categorie = $row["catfield"]:

// has category changed ?
// if so, print it
if ($categorie != $prevCat)  {
	echo "<h2>$categorie</h2>";
}
echo  $title, ' ', $price, '<br/>';

$prevCat = $categorie;
}
?>

 

Please please can someone help me order these correctly instead of me having to enter my data in a particular order as this is not possible because my categories change weekly.

 

Thanks for your help! If you need any questions answered please post and i can try to make what i've said more clear!

Link to comment
Share on other sites

try

<?php
include('odbc.php');
$sql = odbc_exec("select * from Product1 ORDER BY catfield"); // <-- change this line
$prevCat='';
while($row = odbc_fetch_array($sql))
{
$title = $row["titlefield"];
$id = $row["idfield"];
$price = $row["pricefield"];
$categorie = $row["catfield"]:

// has category changed ?
// if so, print it
if ($categorie != $prevCat)  {
	echo "<h2>$categorie</h2>";
}
echo  $title, ' ', $price, '<br/>';

$prevCat = $categorie;
}
?>

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.