Jump to content

mysql_fetch_assoc in while loop


argh2xxx

Recommended Posts

Hello guys,

 

I'm new to php and still learning.  I'm testing this code, and my question is why mysql_fetch_assoc is acting different when it is inside while loop and when it's not.  Check the code below and see what I mean.

 

When mysql_fetch_assoc is in while loop:

echo "<p>";
$commsql = "SELECT name FROM comments WHERE blog_id = " . $row['id'] . " ORDER BY dateposted;";
$commresult = mysql_query($commsql);
$numrows_comm = mysql_num_rows($commresult);

if ($numrows_comm == 0){
echo "<p>No comments.</p>";
}
else {
	echo "(<strong>" . $numrows_comm . "</strong>) comments : ";
	$i = 1;
			while($commrow = mysql_fetch_assoc($commresult)){
		echo "<a href='viewentry.php?id=" . $row['id'] . "#comment" . $i . "'>". $commrow['name'] . "</a> ";

		$i++;
	}
}
echo "</p>";

 

When mysql_fetch_assoc is not in while loop:

echo "<p>";
$commsql = "SELECT name FROM comments WHERE blog_id = " . $row['id'] . " ORDER BY dateposted;";
$commresult = mysql_query($commsql);
$numrows_comm = mysql_num_rows($commresult);

if ($numrows_comm == 0){
echo "<p>No comments.</p>";
}
else {
	echo "(<strong>" . $numrows_comm . "</strong>) comments : ";
	$i = 1;
	$commrow = mysql_fetch_assoc($commresult);		
                        while($commrow){
		echo "<a href='viewentry.php?id=" . $row['id'] . "#comment" . $i . "'>". $commrow['name'] . "</a> ";

		$i++;
	}
}
echo "</p>";

 

The latter is wrong as it will print out same information repeatedly from that echo statement.  Maybe my while loop not supposed to be like that in the latter case?

Link to comment
https://forums.phpfreaks.com/topic/118611-mysql_fetch_assoc-in-while-loop/
Share on other sites

Hi,

 

mysql_fetch_assoc pulls 1 row at a time and then increments the row number - when in a while loop you constantly change the value of $commrow with the new row from your mysql_fetch_assoc statement.

 

When outside the loop you only ever pull the first row and then loop it over and over again.

 

http://uk2.php.net/mysql_fetch_assoc

 

 

Hi,

 

mysql_fetch_assoc pulls 1 row at a time and then increments the row number - when in a while loop you constantly change the value of $commrow with the new row from your mysql_fetch_assoc statement.

 

When outside the loop you only ever pull the first row and then loop it over and over again.

 

http://uk2.php.net/mysql_fetch_assoc

 

 

 

Thanks...

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.