What is the correct way to set a default selected value in a dropdown menu in PHP based on database records?

When populating a dropdown menu in PHP based on database records, you may want to set a default selected value based on a specific record in the database. To achieve this, you can retrieve the database records, loop through them to generate the options for the dropdown menu, and use an if statement to check if the current option matches the default selected value. If it does, you can add the "selected" attribute to that option.

<select name="dropdown">
<?php
$defaultSelectedValue = "example"; // Default selected value based on database record

// Retrieve database records
$records = // Your database query here

foreach($records as $record) {
    $selected = ($record['value'] == $defaultSelectedValue) ? "selected" : "";
    echo "<option value='" . $record['value'] . "' $selected>" . $record['label'] . "</option>";
}
?>
</select>