Page 1 of 1

newbie question on while loop and mysql_fetch_array

Posted: Sat Mar 01, 2008 9:25 pm
by s1akr
Hello every,

I'm sorry if this question is trivial, but I'm a newbie both in programming and PHP, so where goes.

From what I understand through reading, while loops work as follows:

Code: Select all

 
while (expression){
     statements
}
 
Where the statements within the enclosed while loop is continually evaluated until the expression returns false. So, how does the following code work?

Code: Select all

 
$result = mysql_query("SELECT id, name FROM mytable");
 
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    printf("ID: %s  Name: %s", $row[0], $row[1]);  
}
 
Isn't $row = mysql_fetch_array(...) an assignment expression which always returns true when the assignment is successful? I'm getting confused here. So, if the expression evaluates true on the first run, then how can this while loop successfully list through the array in question? I've tried it and it worked beautifully, but am just wondering how it all works. Can someone shine some light on this subject? Much appreciated.

Cheers

Re: newbie question on while loop and mysql_fetch_array

Posted: Sat Mar 01, 2008 9:31 pm
by Sekka
You are right, a while loop runs while the expression is true.

mysql_fetch_array() fetches one record from the result at a time. Everytime it fetches a result successfully, it returns true, allowing the while loop to run again.

When you get to the end of the results the query produced, it will run mysql_fetch_array(), and because there are no more records to return, it returns false, halting the while loop and continuing with the code execution.

That make sense?

Re: newbie question on while loop and mysql_fetch_array

Posted: Sat Mar 01, 2008 9:38 pm
by s1akr
That makes complete sense. I didn't realize fetch_array retrieves one record at a time. Thank you for clearing this up.