While statement using mysql_fetch_assoc()...

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
Wolf_22
Forum Contributor
Posts: 159
Joined: Fri Dec 26, 2008 9:43 pm

While statement using mysql_fetch_assoc()...

Post 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. :banghead:
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Re: While statement using mysql_fetch_assoc()...

Post 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'];
}
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: While statement using mysql_fetch_assoc()...

Post 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.
Post Reply