How can PHP be used to populate dropdown menus with data from an SQL table?
To populate dropdown menus with data from an SQL table using PHP, you can connect to the database, query the table for the data you want to populate the dropdown with, and then loop through the results to create the options for the dropdown menu.
<?php
// Connect to the 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);
}
// Query the SQL table for data
$sql = "SELECT id, name FROM table_name";
$result = $conn->query($sql);
// Create dropdown menu options
echo "<select>";
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
// Close the connection
$conn->close();
?>