What is the best practice for populating a select element with data from a MySQL table in PHP?

When populating a select element with data from a MySQL table in PHP, the best practice is to first establish a connection to the database, retrieve the data from the table using a query, and then loop through the results to generate the options for the select element. This ensures that the select element is dynamically populated with the data from the database.

<?php
// Establish a connection to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');

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

// Retrieve data from the MySQL table
$query = "SELECT id, name FROM table_name";
$result = $connection->query($query);

// Generate options for the select element
echo '<select name="select_name">';
while ($row = $result->fetch_assoc()) {
    echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
echo '</select>';

// Close the connection
$connection->close();
?>