What are potential pitfalls when using PHP to populate select fields with data from a database?

One potential pitfall when using PHP to populate select fields with data from a database is not properly sanitizing the input data, which can lead to SQL injection attacks. To solve this issue, always use prepared statements to prevent malicious SQL injection attacks.

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a statement to select data from the database
$stmt = $pdo->prepare("SELECT id, name FROM my_table");

// Execute the statement
$stmt->execute();

// Populate the select field with the retrieved data
echo '<select name="my_select">';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
echo '</select>';