What are the best practices for dynamically generating navigation menus in PHP using database tables?

When dynamically generating navigation menus in PHP using database tables, it is important to properly structure your database tables to store the necessary information for the menu items, such as the menu item name, URL, and parent-child relationships. Additionally, you should use PHP to query the database and dynamically generate the HTML markup for the navigation menu based on the data retrieved from the database.

<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Query to retrieve menu items from the database
$query = $pdo->query("SELECT * FROM menu_items ORDER BY parent_id, menu_order");

// Build the navigation menu
$menuItems = $query->fetchAll(PDO::FETCH_ASSOC);
echo '<ul>';
foreach ($menuItems as $menuItem) {
    if ($menuItem['parent_id'] == 0) {
        echo '<li><a href="' . $menuItem['url'] . '">' . $menuItem['name'] . '</a>';
        echo '<ul>';
        foreach ($menuItems as $childItem) {
            if ($childItem['parent_id'] == $menuItem['id']) {
                echo '<li><a href="' . $childItem['url'] . '">' . $childItem['name'] . '</a></li>';
            }
        }
        echo '</ul>';
        echo '</li>';
    }
}
echo '</ul>';
?>