What are the potential pitfalls of manually setting the "selected" attribute for dropdown options based on database values in PHP?

When manually setting the "selected" attribute for dropdown options based on database values in PHP, the potential pitfalls include the risk of SQL injection if the database values are not properly sanitized, and the possibility of errors if the database values do not match any of the dropdown options. To solve this issue, it is important to sanitize the database values before using them in the HTML output and to check if the selected value exists in the dropdown options before setting the "selected" attribute.

// Assume $dbValue is the value retrieved from the database
// Assume $dropdownOptions is an array of dropdown options

// Sanitize the database value
$sanitizedDbValue = htmlspecialchars($dbValue);

// Check if the database value exists in the dropdown options
if (in_array($sanitizedDbValue, $dropdownOptions)) {
    echo '<select>';
    foreach ($dropdownOptions as $option) {
        if ($option == $sanitizedDbValue) {
            echo '<option value="' . $option . '" selected>' . $option . '</option>';
        } else {
            echo '<option value="' . $option . '">' . $option . '</option>';
        }
    }
    echo '</select>';
} else {
    echo 'Database value does not match any dropdown options.';
}