Home » Php » How to create dynamic multilevel menu using php and mysql?

How to create dynamic multilevel menu using php and mysql?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’ve been trying to build a dropdown menu but I’m not getting my desired results. Here’s my code:

<?php
$conn = mysqli_connect('localhost', 'root', '  ' );
mysqli_select_db($conn, 'db');

function get_menu_tree( ) 
{
    global $conn;
    $menu = " ";
    $sql = " SELECT * FROM `menu` ";
    $result=mysqli_query($conn,$sql);
    while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) 
    {
           $menu .="<li><a href='".$row['link']."'>".$row['title']."</a>";

           $menu .= "<ul>".get_menu_tree($row['id'])."</ul>"; //call  recursively

           $menu .= "</li>";

    }

    return $menu;
} 
?>
How to&Answers: