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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.