How can PHP be used to manage menu structures with unlimited depth in a MySQL database?

To manage menu structures with unlimited depth in a MySQL database using PHP, we can use a recursive function to retrieve and display menu items. Each menu item should have a parent_id field that links it to its parent item. By recursively querying the database to retrieve all child items of a parent item, we can construct a nested menu structure.

function displayMenu($parent_id = 0) {
    $query = "SELECT * FROM menu WHERE parent_id = $parent_id";
    $result = mysqli_query($connection, $query);
    
    if(mysqli_num_rows($result) > 0) {
        echo "<ul>";
        while($row = mysqli_fetch_assoc($result)) {
            echo "<li>{$row['name']}</li>";
            displayMenu($row['id']);
        }
        echo "</ul>";
    }
}

// Call the function to display the menu
displayMenu();