How can PHP be used to dynamically generate menus based on database entries?

To dynamically generate menus based on database entries in PHP, you can query the database to retrieve the menu items and then loop through the results to generate the menu HTML markup. This allows for easy updates and changes to the menu without having to manually edit the HTML code.

<?php
// Connect to the database
$conn = new mysqli('localhost', 'username', 'password', 'database');

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

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

// Generate the menu based on the database entries
if ($result->num_rows > 0) {
    echo '<ul>';
    while ($row = $result->fetch_assoc()) {
        echo '<li><a href="' . $row['url'] . '">' . $row['title'] . '</a></li>';
    }
    echo '</ul>';
} else {
    echo 'No menu items found';
}

// Close the database connection
$conn->close();
?>