Jump to content

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);

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.