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
https://forums.phpfreaks.com/topic/73466-grouping-my-returned-database-results/
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;
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.