简体   繁体   中英

drop down menu from database

I am want to make a navigation menu with a sub menu on hover. I want to get this data from my database (to make it dynamic if data in database changes menu bar changes). In my database I have a table with the the following fields:

ID , Name , Level , Parent_id . Level can be 0 or 1 . 0 for main menu 1 for sub menu the id of a main menu is tied to the parent_id field.

So for instance:

ID  Name           Level   Parent_id
1   Test           0      
2   Test2          0
3   Test_sub       1        1
4   Test_sub2      2        2

I have managed to get the main menu items from the db but now I am a little bit stuck. This is my code any help would be appriciated.

<?php 
$q2= "SELECT * from menu where level = 0 ";
$q2result = $db->query($q2);
while($a2 = $q2result->fetch(PDO::FETCH_ASSOC)){
    echo "  
 <ul> 
    <li><a href='#' ><span> " . $a2['name'] . "  </span></a>
    <ul>
        <li><a href='#' ><span> test </span></a></li>
    </ul>
</ul>
";  
}
?>

First load all your datas into variables. Never print/echo while in SQL statement.

 <?php 
  $q2= "SELECT * FROM menu ORDER BY Level ASC";
  $q2result = $db->query($q2);
  $nodes=array();
  while($a2 = $q2result->fetch(PDO::FETCH_ASSOC)){
    // assuming one parent node has already been assigned, due do level order into the SQL
    if($node['Level']>0 && isset($nodes[$a2['id']])) {
      $nodes[$a2['id']]['nodes'][]=$a2;
    } else {
      // parent node
      $nodes[$a2['id']]=$a2;
      $nodes[$a2['id']]['nodes']=array();
    }

  }

  print "<ul>";
  foreach($nodes as $node) {
    print "<li>";
      print "<a href='#'>".$node['Name']."</a>";
      if(sizeof($node['nodes'])>0) {
        print "<ul>";
        foreach($node['nodes'] as $subnode) {
          print "<li><a href='#'>".$subnode['Name']."</a></li>";
        }
        print "</ul>";      
      }
    print "</li>";
  }
  print "</ul>";
?>

This may be much more improved, but with this, you can do what you ask, and improve it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM