View Full Version : Newbie: while loop question

02-21-2012, 07:14 PM
I'm learning php/mysql and have 2 very basic questions that I hope someone can help with. I have posted the code that I have been learning and found some problems/questions:

1. what ends the while loop? Does the mysql_query/mysql_fetch_array return null when its done parsing/traversing the array ie how does it know it's reached the end of the row/array?

2. Isn't it bad practice to put a mysql_query command into the "do" part of a loop? (see code below) It looks like the command will be called each time the loop repeats causing multiple unnecessary calls to the same function.


$subject_set = mysql_query("SELECT * FROM subjects", $link);
if (!$subject_set) {
die("Database query failed: " . mysql_error());

while ($subject = mysql_fetch_array($subject_set)) {
echo "<li>{$subject["menu_name"]}</li>";
$page_set = mysql_query("SELECT * FROM pages WHERE subject_id = {$subject["id"]}", $link);
if (!$page_set) {
die("Database query failed: " . mysql_error());

echo "<ul class=\"pages\">";
while ($page = mysql_fetch_array($page_set)) {
echo "<li>{$page["menu_name"]}</li>";
} echo "</ul>";


Any clarification would be greatly appreciated as I need to build up my confidence as well as my kniowledge..:confused:

02-21-2012, 07:24 PM
While completes when any non-true statement occurs. Mysql_fetch_* returns false on an empty recordset, and assigns this value to the variable. The if check is performed on the value of the assigned variable, which turns to be false and terminates the loop.

You do not have a do/while loop here. But the use depends completely on what you want to happen. I don't recommend record iterations in do/while as its pretty much the programmatic way of saying "I guarantee you have something to work with". I strongly recommend that no query should occur within a loop of any sorts; queries should be manufactured to prevent the use of nested looping.

02-21-2012, 10:45 PM
Oops, I forgot that you can have "do/while" loops.. By "do" I meant the action part of the while loop. Thanks for your answer.

I agree (with respect as I'm a total noob at this) that nested loops sound a bit long-winded for this, even though the outcome of the learning exercise was to create a nested list of links to pages.

I can see I'm at the start of a very long journey but with practice I hope to build some decent applications.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum