Jump to content

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 />";
}
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.