I am trying to setup a loop to print out the associated students with the teacher and the script works except for one small issue.
I am trying to only print out the teacher name once and then list all the students under that one teacher
I thought the following code would do it but it is only printing out only one teacher and all the students:
$query = ("
SELECT teachers.teacher_id, students.teacher_id, teachers.teacher_name, students.student_fname, students.student_lname
FROM teachers, students
WHERE teachers.teacher_id = students.teacher_id ORDER BY teachers.teacher_name
");
$result = mysql_query($query) or die(mysql_error());
$prevkey = FALSE;
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result))
{
if ($prevkey != $row['teacher_id']) {
$prevkey = TRUE;
echo "<strong>Teacher: {$row['teacher_name']}</strong><br />";
}
echo "Student:</strong> {$row['student_fname']} {$row['student_lname']}";
echo "<br />";
}
output:
Teacher: Charlotte Newmeyer
Student: Marcus Wiley
Student: Mark Smith
Student: Grayson Simonds
Student: Mike Love
Student: Matt Simonds
Student: Mary Montana
Student: William Smith
Student: Lisa Smook
Student: Mary Bob Throton
Student: Billy Bob Throton
Student: Mike Hunt
Student: Bailey Simonds
Student: George Smith
before I added the switch $prevkey and the if statement inside the while loop, I was getting this output:
Teacher:Charlotte Newmeyer Student: Marcus Wiley
Teacher:Charlotte Newmeyer Student: Mark Smith
Teacher:Charlotte Newmeyer Student: Grayson Simonds
Teacher:Charlotte Newmeyer Student: Mike Love
Teacher:Heather Simonds Student: Matt Simonds
Teacher:Heather Simonds Student: Mary Montana
Teacher:Mike Simonds Student: William Smith
Teacher:Pam Little Student: Lisa Smook
Teacher:Pam Little Student: Mary Bob Throton
Teacher:Pam Little Student: Billy Bob Throton
Teacher:Scott Neymeyer Student: Mike Hunt
Teacher:Scott Neymeyer Student: Bailey Simonds
Teacher:Scott Neymeyer Student: George Smith
I just not get what I am doing wrong
Thanks in advance!!!
Mike