Simple recursive function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
fluidbyte
Forum Commoner
Posts: 30
Joined: Tue May 27, 2008 2:07 pm

Simple recursive function

Post 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);
        
        }
      }
 
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Simple recursive function

Post 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.
fluidbyte
Forum Commoner
Posts: 30
Joined: Tue May 27, 2008 2:07 pm

Re: Simple recursive function

Post by fluidbyte »

The curly brackets did the trick.

Thanks
Post Reply