How can PHP be used to retrieve data from a MySQL table and populate a select element with the results?

To retrieve data from a MySQL table and populate a select element with the results using PHP, you can establish a connection to the database, query the table for the desired data, and then loop through the results to create option elements for the select element.

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

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

// Query the database for the desired data
$query = "SELECT id, name FROM table_name";
$result = mysqli_query($connection, $query);

// Populate the select element with the results
echo "<select>";
while ($row = mysqli_fetch_assoc($result)) {
    echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";

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