Why odes this not work?

Discussion in 'PHP' started by bobby9101, Mar 5, 2007.

  1. #1
    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?
     
    bobby9101, Mar 5, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    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.
     
    nico_swd, Mar 5, 2007 IP