What best practices should be followed when using PHP to display data from a database in a dropdown list?

When displaying data from a database in a dropdown list using PHP, it is important to sanitize the input to prevent SQL injection attacks. Additionally, it is recommended to use prepared statements to securely interact with the database. Finally, make sure to properly loop through the database results and generate the dropdown options dynamically.

<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');

// Prepare and execute the query
$stmt = $pdo->prepare("SELECT id, name FROM table_name");
$stmt->execute();

// Generate the dropdown list
echo '<select name="dropdown">';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
}
echo '</select>';
?>