If I do $fetch = mysql_query("SELECT * FROM forumcats WHERE parentid='0' ORDER BY id ASC"); while ($row = mysql_fetch_array($fetch)) { echo "<b><a href=\"forum.php?category=$row[id]\">$row[name]</a></b><br />"; while ($row2 = mysql_fetch_array(mysql_query("SELECT * FROM forumcats WHERE parentid='$row[id]' ORDER BY name ASC"))) { echo "<a href=\"forum.php?category=$row2[id]\">$row2[name]</a><br />"; } } PHP: it creates an infinite loop, but if I do $fetch = mysql_query("SELECT * FROM forumcats WHERE parentid='0' ORDER BY id ASC"); while ($row = mysql_fetch_array($fetch)) { echo "<b><a href=\"forum.php?category=$row[id]\">$row[name]</a></b><br />"; $fetch2 = mysql_query("SELECT * FROM forumcats WHERE parentid='$row[id]' ORDER BY name ASC"); while ($row2 = mysql_fetch_array($fetch2)) { echo "<a href=\"forum.php?category=$row2[id]\">$row2[name]</a><br />"; } } PHP: it works, why?
Because while() executes the code between the curly brackets while the given condition is true, therefore mysql_query() is called in every loop to verify that. If you call it outside the loop it's only called once, and the resource remains the same and returns false when it reaches the end.