jeff5656 Posted December 10, 2009 Share Posted December 10, 2009 I have a table that displays a bunch of records: <?php $consultsq1 = "SELECT * FROM ild INNER JOIN meds ON ild.id_incr = meds.pt_id AND ild.id_incr = '$id_incr' order by meds.med, meds.startdate"; $result = mysql_query ($consultsq1) or die ("Invalid query: " . mysql_error ()); for($n=0;$row = mysql_fetch_assoc ($result);$n++) { if(!$n) { ?> <table><tr><th >Med</th><th>Dose</th><th>Start Date</th><th >Stop Date</th></tr> <?php } ?> <tr> <td><?php echo $row['med'];?></td> <td><?php echo $row['dose'];?></td> <td><?php echo date("m/d/y ", strtotime($row['startdate']));}?></td> <?php } ?> </table> I want to display the medicine name only the first time ($row['med']) and leave the <td> blank until a record with a different medicine name comes up. How would I do this with the code above? so it would display like this: motrin 50 mg 11/8/09 100 mg 12/8/09 tylenol 500 mg 12/9/09 instead of like this: motrin 50 mg 11/8/09 motrin 100 mg 12/8/09 tylenol 500 mg 12/9/09 Quote Link to comment https://forums.phpfreaks.com/topic/184653-only-display-a-name-once-in-a-for-loop/ Share on other sites More sharing options...
Buddski Posted December 10, 2009 Share Posted December 10, 2009 You need to set a variable that stores the med name.. eg. $name = null; while($row = mysql_fetch_assoc ($result)) { if (is_null($name)) || $name != $row['med']) { echo '<tr> <td>'.$row['med'].'</td> <td>'.$row['dose'].'</td> <td>'.date("m/d/y ", strtotime($row['startdate'])).'</td> </tr>'; $name = $row['med']; } else { echo '<tr> <td> </td> <td>'.$row['dose'].'</td> <td>'.date("m/d/y ", strtotime($row['startdate'])).'</td> </tr>'; } } hope this helps.. Quote Link to comment https://forums.phpfreaks.com/topic/184653-only-display-a-name-once-in-a-for-loop/#findComment-974852 Share on other sites More sharing options...
wildteen88 Posted December 10, 2009 Share Posted December 10, 2009 You'd be better of doing this, otherwise you're just repeating yourself. $prev_med_name = null; while($row = mysql_fetch_assoc ($result)) { $med_name = ($prev_med_name != $row['med']) ? $row['med'] : ' '; echo '<tr> <td>'.$med_name.'</td> <td>'.$row['dose'].'</td> <td>'.date("m/d/y ", strtotime($row['startdate'])).'</td> </tr>'; $prev_med_name = $row['med']; } Quote Link to comment https://forums.phpfreaks.com/topic/184653-only-display-a-name-once-in-a-for-loop/#findComment-974992 Share on other sites More sharing options...
jeff5656 Posted December 10, 2009 Author Share Posted December 10, 2009 Thanks that worked perfectly. Quote Link to comment https://forums.phpfreaks.com/topic/184653-only-display-a-name-once-in-a-for-loop/#findComment-975092 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.