Link187
02-21-2012, 06:14 PM
Hi,
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.
<?php
$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:
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.
<?php
$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: