Grouping Output

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pepe_lepew1962
Forum Commoner
Posts: 44
Joined: Thu Nov 20, 2008 10:29 am

Grouping Output

Post by pepe_lepew1962 »

Hello, I am having problems with displaying grouped records from mysql and could desperately use help. In the example below, I want to display the Order Number ONCE and ALL the records associated with that order. Then carry on to the next record and so on. Here is a sample of what the output is suppose to be. Can anyone help me with this. The key being to not display the Order Number on every line.


tblName1.OrderNumber tblName2.Name tblName2.Price

12653 PBXL 396.52
ABCD 426.28
GEDL 385.20

12654 ABCD 515.18
FGHL 520.00

12659 PBXL 612.35
FGHL 619.20
XTRL 420.39


Thanks.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Grouping Output

Post by social_experiment »

If you have a foreign key in both of the tables you could join them together

EDIT:
If you can change your tables to include 'OrderNumber' in table 2 and have the following columns, the script below will do what you want.
table 1
--------
ordernumber

table 2
-------
name | price | ordernumber

Code: Select all

<?php
$query = "SELECT order_number FROM tblname GROUP By order_number";
$sql = mysql_query($query) or die(mysql_error());
	
while ($result = mysql_fetch_array($sql)) {
 $orderNumberArray[] = $result['order_number'];
}
	
foreach ($orderNumberArray as $orderNumber) {
	echo $orderNumber .'<br />';
	$orderNumberQuery = "SELECT name, price FROM tblname2 
	WHERE order_number = '". mysql_real_escape_string($orderNumber) ."'";
		
	$orderNumberSql = mysql_query($orderNumberQuery) 
	or die(mysql_error());
		
	while ($orderNumberResult = mysql_fetch_array($orderNumberSql)) {			
		echo $orderNumberResult['name'] .' '. $orderNumberResult['price'] .
		'<br />';
	}
}
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply