How can PHP be used to populate dropdown options from a database query?
To populate dropdown options from a database query using PHP, you can first establish a connection to the database, execute a query to fetch the data for the dropdown options, and then loop through the results to generate the HTML options for the dropdown.
// Establish a connection to the database
$connection = new mysqli('localhost', 'username', 'password', 'database_name');
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Execute a query to fetch data for dropdown options
$query = "SELECT id, option_name FROM dropdown_options";
$result = $connection->query($query);
// Generate HTML options for the dropdown
echo "<select>";
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row['id'] . "'>" . $row['option_name'] . "</option>";
}
echo "</select>";
// Close the connection
$connection->close();