How can PHP be used to generate a navigation bar on a website, with menu contents pulled from a database?

To generate a navigation bar on a website with menu contents pulled from a database, you can create a PHP script that queries the database for the menu items and dynamically generates the navigation links using a loop. This allows for easy updating of the menu items without having to modify the HTML code manually.

<?php
// Connect to the database
$connection = mysqli_connect('localhost', 'username', 'password', 'database_name');

// Query to fetch menu items from the database
$query = "SELECT * FROM menu_items";
$result = mysqli_query($connection, $query);

// Generate navigation bar
echo '<ul>';
while ($row = mysqli_fetch_assoc($result)) {
    echo '<li><a href="' . $row['url'] . '">' . $row['name'] . '</a></li>';
}
echo '</ul>';

// Close database connection
mysqli_close($connection);
?>