Page 1 of 1

While Loop Question

Posted: Fri Jan 15, 2010 9:26 pm
by JakeJ
This is more a matter of curiosity than problem solving.

Code: Select all

 
<?php
 
 
$testqry = mysql_query("SELECT * FROM test");
 
#This code works
While ($row = mysql_fetch_array($testqry)) {
    Echo 'HELLO<br>';
}
 
#But this code doesn't
$test = mysql_fetch_array($testqry);
While ($row = $test) {
       Echo 'HELLO<br>'
};
?>
 
It seems to throw me in to an endless loop. Since $test IS the array, why wouldn't it work?

Thanks!

Re: While Loop Question

Posted: Fri Jan 15, 2010 9:40 pm
by AbraCadaver
In your first code it says assign the return of mysql_fetch_array() (an array) to $row each loop iteration, and as long as $row doesn't equal false, keep looping. $row will not equal false until the loop after the last row is fetched from the result $testqry.

In your second example, you have fetched one row and assigned it to $test (an array). Then in your loop it says, assign $test to $row and as long as $row doesn't equal false, keep looping. Since $test equals an array return from the call to mysql_fetch_array() and you assign this each loop iteration to $row, then $row will never be false.

Re: While Loop Question

Posted: Fri Jan 15, 2010 11:10 pm
by SimpleManWeb
AbraCadaver is exactly right. This code should work:

Code: Select all

 
     $test = mysql_fetch_array($testqry);
     While ($row == $test) {
        Echo 'HELLO<br>'
     };
 
 
A single "=" is like SAYING "A Now Equals B" but "==" is like ASKING "Does A now equal B". That's where the problem lies.
So, in the case of your while loop, you want to keep asking "$test" if there are more values. Once it returns false, then the loop will end.

Hope this clears it up.

Re: While Loop Question

Posted: Sat Jan 16, 2010 2:54 am
by kalidG
SimpleManWeb wrote:AbraCadaver is exactly right. This code should work:

Code: Select all

 
     $test = mysql_fetch_array($testqry);
     While ($row == $test) {
        Echo 'HELLO<br>'
     };
 
 
this will not execute
because $row will never be equal to $test
but in the first loop
it is like while we can put array that we pull from the $test do instructions
example:
$test is like that:
[Record 1]----->array
[Record 2]
[Record 3]
[Record 4]
[Record 5]
the mysql_fetch_array parse each record to an array when it is out record it returns false
so $row will be equal to false which exit from the loop

Hope this Help

Re: While Loop Question

Posted: Sat Jan 16, 2010 9:17 am
by JakeJ
Thanks everyone that clears it up. Now I understand perfectly. I've gotten hung up a few times on = vs ==.

Much appreciated!

Posted: Sat Jan 16, 2010 2:41 pm
by Jonah Bron
I don't think the == is the problem. The issue is that every time you call mysql_fetch_array(), it gets the next result from the query. While ($row = mysql_fetch_array($query)) is like saying "If there's another result, get it".