Jump to content

Listing Product Categories and their Product Names - Have mySQL - need some PHP


matto1376

Recommended Posts

Hi guys,

 

I have a mySQL query that returns a product category and product like this:

 

Cat Name 1        Product Name1

Cat Name 1        Product Name2

Cat Name 2        Product Name3

Cat Name 2        Product Name4

Cat Name 2        Product Name5

 

 

Using PHP, how can I out my query so that it only displays the Category name once??

 

ie:

Cat Name 1        Product Name1

                          Product Name2

Cat Name 2        Product Name3

                          Product Name4

                          Product Name5

 

Thanks in advance for any suggestions.

 

 

Something like this will do the trick..

 

$old_cat = null;
while ($data = mysql_fetch_assoc($sql_query)) {
if (is_null($old_cat) || $old_cat != $data['category_name']) {
	echo $data['category_name'];
	$old_cat = $data['category_name'];
}
// echo out your products here
}

Thanks Buddski,

 

Real close....it got rid of the first category and products though.....

So say for example I had initially:

Cat Name 1        Product Name1

Cat Name 2        Product Name2

Cat Name 2        Product Name3

Cat Name 2        Product Name4

Cat Name 3        Product Name5

Cat Name 3        Product Name6

 

Your code would leave me with:

 

Cat Name 2        Product Name2

                          Product Name3

                          Product Name4

Cat Name 3        Product Name5

                          Product Name6

 

So, real close, just dropping off that first category.

 

Am I doing something wrong??

 

Thanks.

 

 

Hi Buddski,

 

All good....I adjusted my ORDER BY in mySQL, I had it ordering by a categoryID - changed it to ordering by itemID and it worked.

 

Now....my next thing is to tabulate the data....I'm not too sure how to display your code in a table....I will try and figure that out now, unless there are any special tricks?

 

Thanks heaps for your help so far!!

When you have the echo $data['category_name']

make that a <tr><td> with a colspan of the whole table.. so it will span all the columns and look like a header..

Then just display the others as normal..

 

$old_cat = null;
while ($data = mysql_fetch_assoc($sql_query)) {
if (is_null($old_cat) || $old_cat != $data['category_name']) {
	echo '<tr><td colspan="2">'.$data['category_name'].'</td></tr>'."\n";
	$old_cat = $data['category_name'];
}
// echo out your products here
echo '<tr>
	<td>'.$data['product_name'].'</td>
	<td>'.$data['price'].'</td>
</tr>'."\n";
}

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.