How can PHP be used to dynamically populate a dropdown list with data from a database?
To dynamically populate a dropdown list with data from a database using PHP, you can retrieve the data from the database using SQL queries and then loop through the results to generate the options for the dropdown list. You can echo out the HTML code for the dropdown list within the PHP code to display it on the webpage.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve data from database
$sql = "SELECT id, name FROM dropdown_data";
$result = $conn->query($sql);
// Generate dropdown list options
echo '<select name="dropdown">';
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
echo '</select>';
// Close database connection
$conn->close();
?>