Jump to content

Only display a name once in a for loop


jeff5656

Recommended Posts

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

 

 

Link to comment
https://forums.phpfreaks.com/topic/184653-only-display-a-name-once-in-a-for-loop/
Share on other sites

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

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'];
}

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.