Page 1 of 1

Simple recursive function

Posted: Mon Jun 02, 2008 12:35 pm
by fluidbyte
I'm trying to build a recursive function to build a tree-style navigation area. Right now I'm just trying to loop out the entries from their database, loading any children nodes below their respective parents. Any idea why this only lists the top level items and won't go any further?

Code: Select all

 
function buildNavStructure($System, $navParent, $navLevel)
      {
      $sql_query = "SELECT * FROM " . $System["tblPrefix"] . "_navigation WHERE navParent=" .
                   $navParent . " ORDER BY navPosition";
      
      $rs = mysql_query($sql_query);
      
      if (!empty($rs))
        {
        while($row = mysql_fetch_array($rs))
        
        echo($row["navText"] . "<br />");
        
        // Check for babies...
        buildNavStructure($System, $row["navID"], $navLevel+1);
        
        }
      }
 

Re: Simple recursive function

Posted: Mon Jun 02, 2008 12:44 pm
by Eran
Your control structures are not well defined so it could be it. Add curly brackets to well-define the while-loop scope for iterating over query results.

Code: Select all

 
while($row = mysql_fetch_array($rs)) {
         echo($row["navText"] . "<br />");
         // Check for babies...
         buildNavStructure($System, $row["navID"], $navLevel+1);
}
 
Second thing, using this kind of recursion is very inefficient due to the large number of sql queries. You are better off retrieving all rows in one query and then use PHP to build the tree structure.

Re: Simple recursive function

Posted: Mon Jun 02, 2008 12:54 pm
by fluidbyte
The curly brackets did the trick.

Thanks