Page 1 of 1
While statement using mysql_fetch_assoc()...
Posted: Sat Jul 11, 2009 10:05 pm
by Wolf_22
Code: Select all
while($get_row = mysql_fetch_assoc()){
//presentation code...
}
I'm having a difficult time understanding what exactly it is that's being done in the while's condition above. I understanding that there is a variable being initialized to that of the mysql_fetch_assoc() function, but to me, that makes no sense because how can something logically happen like that (unless I'm missing something with that function)?
How can anything happen if something is being created during that instance of THAT occurrence-action itself?
With this in mind, does mysql_fetch_assoc() just keep "fetching" until it reaches the end of the table? If that's the case, then I suppose that makes some sense because that would be a logical condition, but if that's NOT the case, then I'm hosed.
Any input on this is very appreciated.

Re: While statement using mysql_fetch_assoc()...
Posted: Sat Jul 11, 2009 10:39 pm
by Skara
does mysql_fetch_assoc() just keep "fetching" until it reaches the end of the table?
yes...sorta. It keeps "fetching" until it reaches the end of what was retrieved from the query.
Code: Select all
$result = mysql_query("SELECT * FROM `table`;");
while ($row = mysql_fetch_assoc($result)) { //note $result goes here
print_r($row);
}
or...
Code: Select all
$res = mysql_query("SELECT `id`,`tag`,`column` FROM `table` WHERE `column` > 5 LIMIT 10;");
//loops a maximum of 10 times because of LIMIT 10:
while ($row = mysql_fetch_assoc($result)) {
echo $row['tag'];
}
Re: While statement using mysql_fetch_assoc()...
Posted: Sat Jul 11, 2009 10:55 pm
by califdon
It's a compact and clever way to code the desired loop to, as Skara explained, fetch successive rows until there are no more to fetch. The thing to focus on is that a while loop (or any other operation that depends on a boolean True/False to execute, such as an if statement) just looks for either a True or a False within the parentheses. How it produces a True or False makes no difference. An assignment statement like "$row=mysql_fetch_row()" will produce a True if it succeeds, but a False if it fails, which it will when there are no more rows to fetch. So, at the same time that it's assigning the next set of values to the $row array, it can also be the "trigger" that determines whether to enter the loop again.