How can a PHP developer effectively utilize PHP's while loop to populate a dropdown list with data from a MySQL database in an efficient manner?
To populate a dropdown list with data from a MySQL database using PHP's while loop efficiently, a developer can fetch the data from the database using a query, then loop through the results using a while loop to create the dropdown options dynamically. This allows for the dropdown list to be populated with the data from the database without having to manually write out each option.
<?php
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query to fetch data from the database
$query = "SELECT id, name FROM table";
$result = mysqli_query($connection, $query);
// Create the dropdown list
echo '<select>';
while ($row = mysqli_fetch_assoc($result)) {
echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
echo '</select>';
// Close the connection
mysqli_close($connection);
?>