What are best practices for handling dropdown menus with values from multiple database tables in PHP?
When handling dropdown menus with values from multiple database tables in PHP, it is best practice to use SQL queries to fetch the necessary data from the tables and then populate the dropdown menu with the retrieved values. This ensures that the dropdown menu is dynamically updated with the latest data from the database tables.
// 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);
}
// Fetch data from multiple tables
$sql_table1 = "SELECT id, name FROM table1";
$result_table1 = $conn->query($sql_table1);
$sql_table2 = "SELECT id, name FROM table2";
$result_table2 = $conn->query($sql_table2);
// Populate dropdown menu with values from table1
echo "<select name='dropdown_table1'>";
while($row = $result_table1->fetch_assoc()) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
// Populate dropdown menu with values from table2
echo "<select name='dropdown_table2'>";
while($row = $result_table2->fetch_assoc()) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
// Close database connection
$conn->close();