How to save dropdown list values ​​when submitting form in php?

Here is the code I wrote, please help me solve this problem.

<select name="gender" id="gender">
                    <option value="M"<?php if(isset($_POST['gender'])=="M"){echo "selected='selected'";}?>>Male</option>
                    <option value="F"<?php if(isset($_POST['gender'])=="F"){echo "selected='selected'";}?>>Female</option>
                    <option value="O"<?php if(isset($_POST['gender'])=="O"){echo "selected='selected'";}?>>Other</option>
                    </select>

When I submit the form, selecting “Male” from the drop-down list, it should save the selected value until I change it in the next view of the form.

In the above code, if I select Male and submit the form, it will show me the others.

so you need a little help. Thanks in advance to those who would like to fix the problem.

+4
source share
3 answers

It will be faster and better if you use below: -

<select name="gender">
<option value="Male" <?php echo (isset($_POST['gender'] && $_POST['gender'] == 'Male')?'selected="selected"':''; ?> >Male</option>
<option value="Female" <?php echo (isset($_POST['gender'] && $_POST['gender'] == 'Female')?'selected="selected"':''; ?> >Female</option>
<option value="Other" <?php echo (isset($_POST['gender'] && $_POST['gender'] == 'other')?'selected="selected"':''; ?> >Other</option>
</select>
+6
source

Assuming you have this:

<select name="gender">
  <option value="Male">Male</option>
  <option value="Female">Female</option>
  <option value="Other">Other</option>
</select>

:

<select name="gender">
  <option value="Male" <?php if ($_POST['gender'] == 'Male') echo 'selected="selected"'; ?> >Male</option>
  <option value="Female" <?php if ($_POST['gender'] == 'Female') echo 'selected="selected"'; ?> >Female</option>
  <option value="Other" <?php if ($_POST['gender'] == 'Other') echo 'selected="selected"'; ?> >Other</option>
</select>
+5

      <option value="M"<?php 
     if(isset($_POST['gender'])=="M")
     --------^^^^^^^^^^^^
    {echo "selected='selected'";}?>>Male</option>

<option value="M"<?php if((!empty($_POST['gender']) && $_POST['gender']=="M")
                      ------^^^^^^^^
   {echo "selected='selected'";}?>>Male</option>
0

All Articles