What are the best practices for iterating through database records and generating HTML options within a select element in PHP?

When iterating through database records to generate HTML options within a select element in PHP, it is important to use a loop to fetch each record and create an option element with the appropriate values. The best practice is to use prepared statements to prevent SQL injection attacks and to properly escape the values to avoid any HTML injection vulnerabilities.

<?php
// Assuming $db is your database connection
$stmt = $db->prepare("SELECT id, name FROM your_table");
$stmt->execute();

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