Eiolon Posted July 16, 2011 Share Posted July 16, 2011 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']; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/242099-trouble-generating-parent-child-list/ Share on other sites More sharing options...
jcbones Posted July 16, 2011 Share Posted July 16, 2011 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']; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/242099-trouble-generating-parent-child-list/#findComment-1243324 Share on other sites More sharing options...
Psycho Posted July 16, 2011 Share Posted July 16, 2011 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); Quote Link to comment https://forums.phpfreaks.com/topic/242099-trouble-generating-parent-child-list/#findComment-1243329 Share on other sites More sharing options...
Eiolon Posted July 16, 2011 Author Share Posted July 16, 2011 Nice, thank you both for your suggestions. Works great! Quote Link to comment https://forums.phpfreaks.com/topic/242099-trouble-generating-parent-child-list/#findComment-1243460 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.