How can a dropdown menu be populated with values from a database in PHP?
To populate a dropdown menu with values from a database in PHP, you can first query the database to fetch the values you want to display in the dropdown menu. Then, iterate over the results and create HTML <option> tags for each value to be displayed in the dropdown menu.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query database to fetch values for dropdown menu
$sql = "SELECT id, name FROM dropdown_values";
$result = $conn->query($sql);
// Create dropdown menu
echo "<select name='dropdown'>";
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
// Close database connection
$conn->close();
?>