Group results by field data ...

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

Group results by field data ...

Post by pepe_lepew1962 »

[text]Hello, I am having problems with grouping records while showing the group data only once. I am trying to get them in a html table that would look like:

+------------------------+----------------------+------------------------+
| tblTable1.fldField1 | tblTable1.fldField2 | tblTable1.fldField3 |
+------------------------+----------------------+------------------------+
| 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 |
+------------------------+----------------------+------------------------+


<?php
//
require("connect.php");
//
$mydata101 = "SELECT tblTable1.fldField1 as 'group', tblTable1.fldField2, tblTable1.fldField3 as 'name' FROM tblTable1 GROUP BY tblTable1.fldField1";
$mydata102 = mysql_query($mydata101);
//
//
$group = null;
while($row = mysql_fetch_array($mydata102))
{
if($row['group'] != $group)
{
echo $row['group'];
$group = $row['group'];
//
$row['name'];
//
}
//
}
?>


Any help would be great appreciated.[/text]
jankidudel
Forum Commoner
Posts: 91
Joined: Sat Oct 16, 2010 4:30 pm
Location: Lithuania, Vilnius

Re: Group results by field data ...

Post by jankidudel »

Here it is, I think you will work little yourself on style :)

Code: Select all

<?php

mysql_connect('localhost', 'root', '');
mysql_select_db('test');

$query = "SELECT  help.field1 , help.field2, help.field3 from help order by help.field1";

$result = mysql_query($query) or die(mysql_error());;

$first_written = false;
if(mysql_num_rows($result) > 0)
{
	echo "<table class='result'  border='1'>";
	while($row = mysql_fetch_assoc($result))
	{	
		echo "<tr>";
		if(!$first_written || $first_written != $row['field1'])
		{
			echo "<td>{$row['field1']}</td>";
			$first_written = $row['field1'];
		}
		else
		{
			echo "<td></td>";
		}
		echo "<td>{$row['field2']}</td>";
		echo "<td>{$row['field3']}</td>";
		echo "</tr>";
	}
	echo "</table>";
}
?>


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

Re: Group results by field data ...

Post by pepe_lepew1962 »

PERFECT !!!
Thank you so much !!!
Post Reply