What is the best practice for populating a dropdown field in HTML with values from a MySQL table using PHP?

When populating a dropdown field in HTML with values from a MySQL table using PHP, the best practice is to first establish a connection to the database, retrieve the data from the desired table, and then loop through the results to generate the options for the dropdown field. This involves using PHP to query the database, fetch the results, and output them as HTML options within the dropdown field.

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

// Check connection
if ($connection === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Query to retrieve data from a table
$query = "SELECT id, name FROM table_name";
$result = mysqli_query($connection, $query);

// Generate dropdown options
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);
?>