What are some best practices for populating a select list with values from a MySQL database in PHP?
When populating a select list with values from a MySQL database in PHP, it is best practice to first establish a connection to the database, retrieve the desired values from a specific table using a SQL query, and then loop through the results to generate the options for the select list.
// Establish a connection to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Retrieve values from a specific table
$sql = "SELECT id, name FROM table_name";
$result = mysqli_query($connection, $sql);
// Generate select list options
echo "<select>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
// Close the connection
mysqli_close($connection);