Jump to content

Trouble generating parent / child list


Eiolon

Recommended Posts

I have two tables, Programs and Sessions.  I want to list the Program once, then all it's sessions beneath it.

 

As of now, I can't quite get the query correct.  If I use a order by clause I get the program listed multiple times, if I use group by clause I get one instance of the program but only one session.

 


$query_programs = "SELECT p.id, p.name AS pname, s.id, s.name AS sname FROM programs p LEFT JOIN sessions s ON (p.id = s.program_id) ORDER BY p.id";
$programs = mysql_query($query_programs) OR die ('SQL query error: Cannot retrieve program information.');
$row_programs = mysql_fetch_assoc($programs);

<?php

$last = '0'; 
while ($row_programs = mysql_fetch_assoc($programs)) { 
if($row_programs['id'] != $last){ 
	echo '<b>' . $row_programs['pname'] . '</b><br>'; 
} 
echo $row_programs['sname'] . '<br>'; 
$last = $row_programs['pname']; 
}  

?>

Link to comment
https://forums.phpfreaks.com/topic/242099-trouble-generating-parent-child-list/
Share on other sites

Study this:

<?php

$last = '0'; 
while ($row_programs = mysql_fetch_assoc($programs)) { 
if($row_programs['id'] != $last){ //the programs ID, will never match the programs NAME.
	echo '<b>' . $row_programs['pname'] . '</b><br>'; 
} 
echo $row_programs['sname'] . '<br>'; 
$last = $row_programs['pname']; 
}  

?>

 

Suggested fix.

<?php

$last = '0'; 
while ($row_programs = mysql_fetch_assoc($programs)) { 
if($row_programs['id'] != $last){ 
	echo '<b>' . $row_programs['pname'] . '</b><br>'; 
} 
echo $row_programs['sname'] . '<br>'; 
$last = $row_programs['id']; 
}  

?>

I would make one change to that. I would put this line . . .

	$last = $row_programs['id']; 

 

. . . inside the if() condition block of code. There is no need to redefine $last on every iteration - only when a change occurs.

 

 

Also, remove this line that you have before the while() loop. Otherwise you will not get the first record in your displayed results

$row_programs = mysql_fetch_assoc($programs);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.