What best practices should be followed when populating dropdown menus with data from a database in PHP?

When populating dropdown menus with data from a database in PHP, it is important to sanitize the input to prevent SQL injection attacks. Additionally, you should use prepared statements to securely query the database and retrieve the data to populate the dropdown menu. Finally, loop through the retrieved data and dynamically generate the options for the dropdown menu.

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

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

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