What are some common pitfalls to avoid when using PHP to output data from a database into a dropdown menu?
One common pitfall to avoid when using PHP to output data from a database into a dropdown menu is not properly escaping the data to prevent SQL injection attacks. To solve this issue, always use prepared statements with parameterized queries to securely retrieve data from the database.
// Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare statement
$stmt = $pdo->prepare('SELECT id, name FROM mytable');
// Execute statement
$stmt->execute();
// Create dropdown menu
echo '<select name="dropdown">';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="' . htmlspecialchars($row['id']) . '">' . htmlspecialchars($row['name']) . '</option>';
}
echo '</select>';