PDA

View Full Version : Grouping Output Data



oriecat
09-20-2006, 11:46 PM
I am trying to pull all info from my database and then have it grouped by the Branch field. I need to manually include a header about each Branch. So it would be like

Header1
list1

Header2
list2

etc

I can get
Header1
list1

or
Header1
list1
list2

but I can't get what I am trying to do. I am really new at this, so I am probably missing something simple. This is what I have so far. I've been moving parts all around trying to make things work, so it's probably really wacked by now... thanks for any thoughts. :)


mysql_pconnect("localhost","***","***");
mysql_select_db("*****");
$result = mysql_query("SELECT * FROM evolinks ORDER BY Branch, Name");

echo "<h2>Portland Emails</h2><br>";
while ($myrow = @mysql_fetch_array($result)) {

if ($myrow["Branch"] == 03) {
echo "<A HREF=mailto:\"",$myrow["email"],"\">",$myrow["Name"];
echo "</A> ","<BR>";
}
}

mwinter
09-22-2006, 03:06 PM
I am trying to pull all info from my database and then have it grouped by the Branch field. I need to manually include a header about each Branch. So it would be like

Header1
list1

Header2
list2

You can approach this in two ways.

The first is to perform the query in two parts. The initial step is to obtain a list of all branches with the query:

&#160;&#160;SELECT DISTINCT Branch FROM evolinks

If you want the branches in a particular order, you can add an ORDER BY clause. You would then loop through that result set, outputing the header on each iteration. Within that loop, you'd also make a second query:

&#160;&#160;SELECT Name, email, ... FROM evolinks WHERE Branch='...'

using the branch value obtained from the first query. Again, you can order the results, and, using a loop, output the data for each result.


The second approach is to use the existing query:

&#160;&#160;SELECT * FROM evolinks ORDER BY Branch, Name

and remember the branch value. On each iteration, you'd check the previous value against the new one and when it changes, you know that you have to output a new header before continuing.



echo "<h2>Portland Emails</h2><br>";

Headings carry an implicit line break, so the br element is unnecessary. If you're trying to introduce more space, don't use a br element, but change the bottom margin using CSS.



echo "<A HREF=mailto:\"",$myrow["email"],"\">",$myrow["Name"];
echo "</A> ","<BR>";

If you're writing a list of links, consider using a list (ul element) instead of line breaks, styling away the list marker with CSS, if desired.

Mike

oriecat
09-22-2006, 06:00 PM
Thanks so much! :) I'll see what I can do with this...