I have a dropdown of blood type, and the values are hardcode, but when entering the interface, which is the best way to set the value previously saved from the database, I'm doing something like this:
<select class="selectpicker" id="'.$key.'" name="'.$key.'">
<optgroup label="Grupo A">';
$sel = ($value == 'A+') ? 'selected' : '' ;
echo '<option value="A+" '.$sel.'>A positivo</option>';
$sel = ($value == 'A-') ? 'selected' : '' ;
echo '<option value="A-" '.$sel.'>A negativo</option>
</optgroup>
<optgroup label="Grupo B">';
$sel = ($value == 'B+') ? 'selected' : '' ;
echo '<option value="B+" '.$sel.'>B positivo</option>';
$sel = ($value == 'B-') ? 'selected' : '' ;
echo '<option value="B-" '.$sel.'>B negativo</option>
</optgroup>
<optgroup label="Grupo AB">';
$sel = ($value == 'AB+') ? 'selected' : '' ;
echo '<option value="AB+" '.$sel.'>AB positivo</option>';
$sel = ($value == 'AB-') ? 'selected' : '' ;
echo '<option value="AB-" '.$sel.'>AB negativo</option>
</optgroup>
<optgroup label="Grupo O">';
$sel = ($value == 'O+') ? 'selected' : '' ;
echo '<option value="O+" '.$sel.'>O positivo</option>';
$sel = ($value == 'O-') ? 'selected' : '' ;
echo '<option value="O-" '.$sel.'>O negativo</option>
</optgroup>
</select>
What is the best way to put the "selected" attribute to an option of a select with a value from a database?