What is the best practice for setting a selected value in an HTML option tag using PHP within a while loop?
When setting a selected value in an HTML option tag using PHP within a while loop, you can use an if statement to check if the current option value matches the selected value. If it does, you can add the "selected" attribute to that option tag. This way, the correct option will be pre-selected when the page loads.
<select name="example">
<?php
while ($row = $result->fetch_assoc()) {
$selected = ($row['value'] == $selectedValue) ? 'selected' : '';
echo "<option value='{$row['value']}' $selected>{$row['name']}</option>";
}
?>
</select>