Jump to content

How to check if loop is at the last or first mysql row result


Jaguar

Recommended Posts


$count = 1;

while($row = mysql_fetch_assoc($result))
{
if(mysql_num_rows($result) == $count))
{
	$site_title = $row['title'];
}

// other code here

$count++;
}

 

Is there a better way to do this without using a count variable? I don't want the title variable to get assigned for every loop, I just want it to be assigned once.

A better way than that would be...

 

$count = 1;

while($row = mysql_fetch_assoc($result))
{
if($count == 1)
{
	$site_title = $row['title'];

	$count++;
}

// other code here
}

 

I was trying to avoid creating a variable. I was hoping there was a way to use functions something like...

 

if(mysql_num_rows($result) == function_that_checks_what_number_row_this_is($row))
{
$site_title = $row['title'];
}

Why don't you want the title to be assigned every time? Does that value change? Worried about performance? Only other way is to make a condition.  But since the condition will be checked every single iteration...you really aren't saving on performance; you're just trading one thing for the other.  But nonetheless, you can simply just check to see if $site_title exists inside your condition:

 

while($row = mysql_fetch_assoc($result))
{
   if (!$site_title) $site_title = $row['title'];
   
   // other code here
}

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.