What is the best way to populate a drop-down menu with values from a database in PHP?
To populate a drop-down menu with values from a database in PHP, you can first retrieve the values from the database using SQL queries. Then, loop through the results to create the options for the drop-down menu using HTML. Finally, echo out the HTML code to display the drop-down menu with the populated values.
<?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);
}
// Retrieve values from the database
$sql = "SELECT id, name FROM table";
$result = $conn->query($sql);
// Create drop-down menu 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();
?>
Keywords
Related Questions
- In what ways can PHP developers ensure that data from different models can access and interact with the same variables in the view within an MVC architecture?
- How can the code provided be modified to avoid the need for square brackets when decoding JSON data in PHP?
- Are there any specific settings or configurations needed on GMX accounts to properly display HTML emails sent via PHP?