amircisija amircisija - 7 days ago 6
MySQL Question

PHP - Foreach loop - echo selected value

I've made something like a crud system for employees.

The user can input informations about the employees. Under others, there is a 'select' input with couple of options that come from the database. When I fill out the form, and submit it, the data gets to the database.

But when I want to edit the form, the 'select' input gets another value, even if I don't change anything there. So I need something to echo the already inputed value from the option.

This is my foreach loop that I use to loop the categories:

<?php
$i = 0;
foreach($categories as $key => $category) {
?>
<option value="<?php echo $category; ?>"><?php echo $category; ?></option>
<?php
$i++;
}
?>


How to get the value from the database that was selected and stored there.
Thanks

Answer

HTML <option> tag has property selected that you should use, it specifies that an option should be pre-selected:

<?php
$i = 0;
$selected_category = "B"; // category value from database
foreach($categories as $key => $category) {
    $selected = ($selected_category == $category) ? "selected" : "";
?>
    <option value="<?php echo $category; ?>" <?php echo $selected; ?>>
    <?php echo $category; ?></option>
<?php
    $i++;
}
?>