I have a blood type dropdown, and the values are hardcoded, but when I enter the interface, what is the best way to set the previously saved value from the database, I am 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?
Although you will have the values hardcoded, you can store them in an array and iterate over it to make it easier to modify and read, as well as use string interpolation instead of concatenations to write less code:
First you declare your combo and you query the Database and when you fill it with values you can validate if the value of the DB matches the value of your combo.
Best regards,