What are the best practices for handling dynamic menu content from a database in PHP?

When handling dynamic menu content from a database in PHP, it is best practice to use a database query to retrieve the menu items and then loop through the results to dynamically generate the menu. This allows for easy maintenance and updating of menu items without having to manually edit the HTML code.

<?php
// Connect to your database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query to retrieve menu items from database
$sql = "SELECT * FROM menu_items";
$result = $conn->query($sql);

// Generate dynamic menu
if ($result->num_rows > 0) {
    echo "<ul>";
    while($row = $result->fetch_assoc()) {
        echo "<li><a href='" . $row["url"] . "'>" . $row["name"] . "</a></li>";
    }
    echo "</ul>";
} else {
    echo "0 results";
}

$conn->close();
?>