Page 1 of 1

displaying data only on the first time through a loop.

Posted: Mon Jun 27, 2005 12:57 pm
by dpayton
I want to display a header on a loop only if the conditional is true and only on the first pass through. Below is the code that I used. Do I have something in the wrong place? This seems to set off an infinite loop.

Code: Select all

$query = "select * from offices where siteid = $siteid";
 $query_result = mysql_query($query) or die(mysql_error());
$i=0;
 while($row = mysql_fetch_array($query_result)) {
 while($i < 1) {
 print "<p><strong>Office locations: </strong></p>";
 }
 print "<p>{$row[1]}, {$row[2]}</p>";
 if (!empty($row[3])) {
  print "<p>{$row[3]}</p>";
 } 
 $i++;
 }
Thanks in advance!

Posted: Mon Jun 27, 2005 1:20 pm
by Burrito
why not just use an if instead of your second while:

Code: Select all

$i=0;
while($row = mysql_fetch_assoc($result)){
  if($i==0)
    // do stuff
  $i++;
}

Posted: Mon Jun 27, 2005 1:54 pm
by dpayton
That worked. Thanks!

Posted: Mon Jun 27, 2005 8:20 pm
by harrisonad
Burrito wrote:

Code: Select all

$i=0;
while($row = mysql_fetch_assoc($result)){
  if($i==0)
    // do stuff
  $i++;
}
This uses up memory inefficiently because you are storing incremented values to $i.
Why not use boolean instead.

Code: Select all

$first_time = true;
while($row = mysql_fetch_assoc($result)){
  if($first_time)
    // do stuff
  $first_time = false;
}

Posted: Tue Jun 28, 2005 2:41 am
by timvw
But you still spend cpu time on testing $first_time every time you cycle through the loop...

Code: Select all

$first_row = mysql_fetch_assoc($rs);
if ($first_rows)
{
  // do stuff with first row
}
while ($row = mysql_fetch_assoc($rs))
{
  // do stuff with other rows
}