Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2006
    Posts
    41

    Unanswered: how to display links and sublinks from a mysql database

    Hi,

    I have a database setup as follows:

    Code:
    id   link_title          parent
    
    1   toplink 1              0
    2   toplink 2              0
    3   toplink 3              0
    4   toplink 4              0
    5   sublink 1a            1
    6   sublink 1b            1
    7   subsublink1c        5
    8   subsublink1d        5
    so the linking structure is

    toplink 1
    ->sublink 1a
    -->subsublink1c
    -->subsublink1d
    ->sublink 1b
    toplink 2
    toplink 3
    toplink 4

    I have made the following function:

    PHP Code:
    function getChild($id)
    {
        require_once(
    'includes/DbConnector.php');
        
    $connector = new DbConnector();
        
        
    //print the title
        
    $query "SELECT * FROM top_menu WHERE id='$id'";
          if(
    $result $connector->query($query))
        {    
            
    $row $connector->fetchArray($result);
            
    $title $row['title'];        
            
             print(
    "<br>");
             print(
    $title);
        }
        
        
    //check if children and print their title
        
    $query "SELECT * FROM top_menu WHERE parent='$id'";
          if(
    $result $connector->query($query))
        {    
            while(
    $row $connector->fetchArray($result))
            {
                
    $id=$row['id'];
                
    getChild($id);
            }        
        }
        

    which is called as follows:

    PHP Code:
    $query "SELECT * FROM top_menu WHERE parent='0'"
    if(
    $result $connector->query($query))
    {
        while(
    $row $connector->fetchArray($result))
        {
              
    $id $row['id'];
             
    getChild($id);          
        }    

    which displays the links in order i.e

    toplink 1
    sublink 1a
    subsublink1c
    subsublink1d
    sublink 1b
    toplink 2
    toplink 3
    toplink 4

    but I can't quite figure out how to make it distinguish between the different levels when it prints out the links so it would be like

    toplevel
    ->sublevel
    -->subsublevel
    ->sublevel
    -->subsublevel
    --->subsubsublevel
    toplevel
    ->sublevel
    ->sublevel
    ...
    ..etc


    Any ideas.

    Cheers

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    you're doing a query inside a loop -- extremely inefficient

    use a single join query instead

    see Categories and Subcategories
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •