How can PHP be used to retrieve data from a MySQL database and populate dropdown lists with that data?

To retrieve data from a MySQL database and populate dropdown lists with that data using PHP, you can establish a connection to the database, execute a query to fetch the data, and then iterate over the results to create the dropdown options. Finally, output the HTML code for the dropdown list with the populated options.

<?php
// Establish connection to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Execute query to fetch data
$sql = "SELECT id, name FROM table";
$result = $conn->query($sql);

// Populate dropdown list with data
echo "<select name='dropdown'>";
while ($row = $result->fetch_assoc()) {
    echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";

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