How can PHP be used to populate dropdown lists with values from a database?
To populate dropdown lists with values from a database using PHP, you can first establish a connection to the database, query the database for the values you want to populate the dropdown with, and then loop through the results to create the dropdown options.
<?php
// Establish a connection to the database
$connection = mysqli_connect('localhost', 'username', 'password', 'database_name');
// Query the database for values
$query = "SELECT id, name FROM table_name";
$result = mysqli_query($connection, $query);
// Create the dropdown list
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
- How can PHP developers optimize their code to efficiently process multiple checkbox selections?
- What are some alternative approaches to organizing and displaying data in PHP applications?
- What are the security implications of using cookies versus IP-based tracking for visitor counting in PHP applications?