newbie question on while loop and mysql_fetch_array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
s1akr
Forum Newbie
Posts: 2
Joined: Sat Mar 01, 2008 9:08 pm

newbie question on while loop and mysql_fetch_array

Post 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
User avatar
Sekka
Forum Commoner
Posts: 91
Joined: Mon Feb 18, 2008 10:25 am
Location: Huddersfield, West Yorkshire, UK

Re: newbie question on while loop and mysql_fetch_array

Post 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?
s1akr
Forum Newbie
Posts: 2
Joined: Sat Mar 01, 2008 9:08 pm

Re: newbie question on while loop and mysql_fetch_array

Post by s1akr »

That makes complete sense. I didn't realize fetch_array retrieves one record at a time. Thank you for clearing this up.
Post Reply