What are the best practices for handling database queries in PHP to populate dropdown menus?
When populating dropdown menus in PHP using database queries, it is important to follow best practices to ensure security and efficiency. One common approach is to retrieve the data from the database using a query, loop through the results to create the dropdown options, and then output the HTML for the dropdown menu.
// Establish a database connection
$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);
}
// Query to retrieve data for dropdown menu
$sql = "SELECT id, name FROM dropdown_data";
$result = $conn->query($sql);
// Create dropdown menu options
if ($result->num_rows > 0) {
echo "<select name='dropdown'>";
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"] . "'>" . $row["name"] . "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
// Close database connection
$conn->close();