Loop results from MySQL DB

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
senojeel
Forum Newbie
Posts: 4
Joined: Tue Nov 02, 2004 8:38 am

Loop results from MySQL DB

Post by senojeel »

I think this is probably a simple thing to do, except I don't have good PHP chops yet.

I want to return a list of names from a MySQL db grouped by section, with the section being a header.

Example:

Violin I
Name One
Name Two
Name Three

Violin II
Name One
Name Two
Name Three

Viola
Name One
etc...

It would be great if I could get a starting point with the code. My fields are section, firstName, lastName. My table is members.

Thanks!
Shawn
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Code: Select all

SELECT * FROM members ORDER BY section ASC, lastName ASC, firstName ASC";

Code: Select all

<?php
$section = '';
while ($row = mysql_fetch_assoc($result)) {
  if ($section != $row['section'])
  {
     echo "<b>Section</b></br>";
     $section = $row['section'];  
  }
  echo $row['lastName'] . ' ' . $row['firstName'] . '</br>';
}
?>
senojeel
Forum Newbie
Posts: 4
Joined: Tue Nov 02, 2004 8:38 am

Post by senojeel »

Thanks for you response timvw.

When I try to use that, I get a parse error: "Parse error: parse error, unexpected '{' in /Users/philharmonicindy/Sites/members/test1.php on line 70"

Line 70 in my page is the "{" in line 5.

Any ideas?
Draco_03
Forum Regular
Posts: 577
Joined: Fri Aug 15, 2003 12:25 pm
Location: Montreal, Canada

Post by Draco_03 »

is your query is saved in $result ?

Code: Select all

$sql="SELECT * FROM members ORDER BY section ASC, lastName ASC, firstName ASC";
$result = mysql_query($sql) or die(MySQL_error());
like that
senojeel
Forum Newbie
Posts: 4
Joined: Tue Nov 02, 2004 8:38 am

Post by senojeel »

I had something like that. I inserted yours and still got the error. Here is my code.

Code: Select all

<?php
$connection = mysql_connect("$server","$username","$password");

$sql="SELECT * FROM members ORDER BY section ASC, lastName ASC, firstName ASC";
$result = mysql_query($sql) or die(MySQL_error());

$section = '';
while ($row = mysql_fetch_assoc($result)) &#123;
  if ($section != $row&#1111;'section'])
&#123;
	echo "<b>Section</b></br>";
	$section = $row&#1111;'section'];  
  &#125;
  echo $row&#1111;'lastName'] . ' ' . $row&#1111;'firstName'] . '</br>';
&#125;
?>
senojeel
Forum Newbie
Posts: 4
Joined: Tue Nov 02, 2004 8:38 am

Post by senojeel »

I got it to work. There must have been some gremlins in the code when I copy and pasted. So I keyed everything back in manually.

Thanks!
Shawn
Post Reply