Jump to content

Why does this happen with mysql_fetch_array ?


TheStalker

Recommended Posts

Hi everyone,

 

Bit of a random question and im sure there is good reason so if someone could in lighten me that would be great !

 

With regards to the below code, it seems to just create an infinite loop when you put mysql_fetch_array. Just want to know what wrong with doing this? and why it act in this way ?

 

$sql = mysql_query("SELECT * FROM cities");
$results = mysql_fetch_array($sql);



while($row = $results)
{
echo $row['City']."<br />";
}

 

 

thanks Guys

A while() loop continues as long as the condition is true. In the above code you are simply attempting to assign the value of $results to $row. $results was already defined before the loop and equals the first record from the result set. So that condition is simply reassigning $results to $row on each iteration. You aren't getting any new records so $results is basically a static variable. You might was well write the condition as

while($foo = 'bar') {

 

Whereas

$sql = mysql_query("SELECT * FROM cities");

while($row = mysql_fetch_array($sql))
{
echo $row['City']."<br />";
}

 

The condition in this loop is fetching the next record from the result set and assigning the value to $row. When the result set runs out of records the resulting condition is false and the loop ends.

You are just assigning the $results array to $row, which is always true if the fetch was successful, so the loop never ends.  What you want is:

 

$sql = mysql_query("SELECT * FROM cities");

while($row =  mysql_fetch_assoc($sql))
{
echo $row['City']."<br />";
}

Because

$results = mysql_fetch_array($sql);

always equates to true in your loop

while($row = $results)

 

Here's how it should be written.

 

<?php
$result = mysql_query("SELECT * FROM cities");
while($row = mysql_fetch_assoc($result))
{
echo $row['City']."<br />";
}
?>

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.