How can PHP be used to retrieve data from a database for a dropdown menu in a form?

To retrieve data from a database for a dropdown menu in a form using PHP, you can query the database for the desired data and then loop through the results to create the dropdown options. This can be achieved by using PHP's database connection functions in conjunction with HTML form elements.

<?php
// Establish a database connection
$conn = mysqli_connect("localhost", "username", "password", "database");

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

// Query to retrieve data for dropdown menu
$sql = "SELECT id, name FROM dropdown_data";
$result = mysqli_query($conn, $sql);

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

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