How can multiple dropdown menus be populated with different data from a single SQL query in PHP?
To populate multiple dropdown menus with different data from a single SQL query in PHP, you can fetch the data from the query once and then use it to populate each dropdown menu individually. You can store the fetched data in an array and then loop through the array to create each dropdown menu with the corresponding data.
<?php
// Perform SQL query to fetch data
$query = "SELECT column1, column2 FROM table";
$result = mysqli_query($connection, $query);
// Fetch data into an array
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
// Populate first dropdown menu
echo "<select name='dropdown1'>";
foreach ($data as $row) {
echo "<option value='" . $row['column1'] . "'>" . $row['column1'] . "</option>";
}
echo "</select>";
// Populate second dropdown menu
echo "<select name='dropdown2'>";
foreach ($data as $row) {
echo "<option value='" . $row['column2'] . "'>" . $row['column2'] . "</option>";
}
echo "</select>";
?>
Related Questions
- What are the common challenges faced by PHP beginners when working with file extensions in Windows Vista?
- How can the problem of the datepicker only appearing for one input field, instead of both, be addressed in PHP?
- What is the purpose of using GROUP BY in a MySQL query when selecting multiple columns?