How can PHP be used to populate a dropdown menu with values from a database?
To populate a dropdown menu with values from a database using PHP, you can first establish a connection to the database, retrieve the values you want to display in the dropdown, and then loop through those values to create the options for the dropdown menu.
// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database_name");
// Retrieve values from the database
$query = "SELECT id, name FROM table_name";
$result = mysqli_query($connection, $query);
// Create the dropdown menu
echo "<select>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
// Close the database connection
mysqli_close($connection);
Keywords
Related Questions
- In what scenarios would it be more appropriate to assign a string value in single quotes before passing it to preg_match_all in PHP?
- How can whitespace in string comparisons affect the outcome in PHP programming?
- How can PHP be integrated with frontend frameworks like Joomla to create dynamic and interactive web applications?