0
votes

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

1
have u looked in your database if it is properly storing those exact values which u submitted? - Rasika
@Rasika it does. It work well, until I want to edit users profile. Then, even if I don't touch the select input, it get's a new value. Let's say there are 4 options (a,b,c,d), first time I choose 'b'. It get's stored as 'b'. Later when I edit any info on the profile the value of the select input get's overwritten by lets say 'a'. - amircisija
then the problem must be in your "update" query or its values. hows it possible that it changes its value automatically? does it shows the exact data in database which u edit and updated. - Rasika
Readability... Is $categories data from your SQL query? Or are you asking how to connect to a Database and output each category associated within the database corresponding to that array? It's pretty unclear, like your code. - Jaquarh
What are you doing with $i++ ? For what you need it? - Twinfriends

1 Answers

5
votes

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++;
}
?>