How can a dropdown menu be populated with values from a MySQL database in PHP?

To populate a dropdown menu with values from a MySQL database in PHP, you can first establish a connection to the database, query the database for the values you want to populate the dropdown menu with, and then loop through the results to create the dropdown options.

<?php
// Establish connection to MySQL database
$connection = mysqli_connect('localhost', 'username', 'password', 'database');

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Query to fetch values from database
$query = "SELECT id, name FROM table_name";
$result = mysqli_query($connection, $query);

// Create dropdown menu
echo '<select name="dropdown">';
while ($row = mysqli_fetch_assoc($result)) {
    echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
echo '</select>';

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