How can a dropdown list be populated with values from a MySQL query in PHP?
To populate a dropdown list with values from a MySQL query in PHP, you can first fetch the data from the database using a SELECT query. Then, loop through the results and create an option element for each value to be displayed in the dropdown list.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Fetch data from database
$query = "SELECT id, name FROM table";
$result = mysqli_query($connection, $query);
// Create dropdown list
echo '<select name="dropdown">';
while ($row = mysqli_fetch_assoc($result)) {
echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
echo '</select>';
// Close database connection
mysqli_close($connection);
?>