displaying data only on the first time through a loop.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dpayton
Forum Newbie
Posts: 10
Joined: Fri Jun 24, 2005 1:48 pm

displaying data only on the first time through a loop.

Post 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!
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post 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++;
}
dpayton
Forum Newbie
Posts: 10
Joined: Fri Jun 24, 2005 1:48 pm

Post by dpayton »

That worked. Thanks!
User avatar
harrisonad
Forum Contributor
Posts: 288
Joined: Fri Oct 15, 2004 4:58 am
Location: Philippines
Contact:

Post 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;
}
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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
}
Post Reply