Search code examples
phpsqlloopsdynamicsubmenu

dynamic multi level dropdown menu php sql


I have nav menu in html and i want to create a loop everything is fine but the item that have children echo twice! i know where is the problem but i can't figure out how to solve it :( my sql table named menu

and this is my php:

      $db = mysqli_connect('localhost', 'root', 'password', 'aftab');
<?php
$get = mysqli_query($db , "SELECT * from menu where parent_id is NULL");
while ($rowmenu = mysqli_fetch_assoc($get)) {
    echo '<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-656"><a href="'. $rowmenu['link'] . '" >' . $rowmenu['name'] .'</a>' ;
    $id = $rowmenu['id'] ;
    $check = mysqli_query($db , "SELECT * from menu where parent_id = '$id'");
    if ( mysqli_num_rows($check) ) { 
         echo '<li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-656"><a href="'. $rowmenu['link'] . '" >' . $rowmenu['name'] .'</a>' ; 
         echo '<ul class="sub-menu">' ;
        while ( $row2 = mysqli_fetch_assoc($check) ) {
            echo '<li class="menu-item-302"><a href="' . $row2['link'] . '">' . $row2['name'] . '</a></li>' ;
        }
        echo '</ul>' ;
    } else {
        echo '</li>' ;
    }
}

?>

and this the result:enter image description here

i know it happen because the father item that hold the sub menu's called in $get once and another time when it need other css class.i tried if , foreach , while and many things. i need that item that holds submenus should have "menu-item-has-children" class otherwise its not show the sub menus.


Solution

  • When a menu item, have childrens then echo menu with menu-item-has-children class, otherwise echo a simple menu and move on.

    <?php
    
    $get = mysqli_query($db , "SELECT * from menu where parent_id is NULL");
    while ($rowmenu = mysqli_fetch_assoc($get)) {
        $id = $rowmenu['id'] ;
        $check = mysqli_query($db , "SELECT * from menu where parent_id = '$id'");
        $haveSubMenu = mysqli_num_rows($check);
    
        if($haveSubMenu)
            echo '<li class="menu-item menu-item-type-post_type menu-item-object-page  menu-item-656 menu-item-has-children"><a href="'. $rowmenu['link'] . '" >' . $rowmenu['name'] .'</a>' ;
        else
            echo '<li class="menu-item menu-item-type-post_type menu-item-object-page  menu-item-656"><a href="'. $rowmenu['link'] . '" >' . $rowmenu['name'] .'</a>' ;
    
        if ($haveSubMenu) 
        { 
            echo '<ul class="sub-menu">' ;
            while ( $row2 = mysqli_fetch_assoc($check) ) {
               echo '<li class="menu-item-302"><a href="' . $row2['link'] . '">' . $row2['name'] . '</a></li>' ;
            }
            echo '</ul>' ;
        } else {
            echo '</li>' ;
        }
    }
    
    ?>