What are common pitfalls when retrieving data from a database to populate a dropdown menu in PHP?
One common pitfall when retrieving data from a database to populate a dropdown menu in PHP is not properly sanitizing the data, which can lead to SQL injection attacks. To solve this issue, always use prepared statements and parameterized queries to prevent SQL injection vulnerabilities.
<?php
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a statement to retrieve data from the database
$stmt = $pdo->prepare("SELECT id, name FROM dropdown_options");
// Execute the statement
$stmt->execute();
// Populate the dropdown menu with the retrieved data
echo '<select name="options">';
while ($row = $stmt->fetch()) {
echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
echo '</select>';
// Close the database connection
$pdo = null;
?>