PHP如果变量等于下拉列表中的值,则将“selected”属性添加到选项中

PHP如果变量等于下拉列表中的值,则将“selected”属性添加到选项中

问题描述:

I have a drop down menu that checks whether a user has already selected a value by checking database and if they have, I want to add a 'selected' attribute to that option so that when they edit their profile, that option is preselected by what they chose.

Heres an example of what I am trying to accomplish. It works for text inputs but I don't know how to do it with dropdown lists.

So if user selects 'Dog', it gets place in database and adds 'selected' as attribute

$animal = $mysqli->escape_string($_POST['animal']);
//PHP UPDATE database script -------->

<label>Animal</label></br>
    <select name='animal' value='<?php if($animal == value){ /*Add selected attribute to option */ ?>'>
         <option value="" disabled selected>Select One</option>
         <option value="" disabled>----------------</option>
         <option value="Dog">Dog</option>
         <option value="Cat">Cat</option>
         <option value="Bird">Bird</option>  
    </select>

Define an array of options

$animals = ['Dog', 'Cat', 'Bird'];

Then generate the list of options for the <select> from that array, checking the selected animal against each one. If it matches, then add the selected attribute.

<label>Animal</label></br>
<select name='animal'>
     <!-- select the default if none of the options are selected -->
     <option value="" disabled <?php if (!in_array($animal, $animals)) echo 'selected' ?>>
         Select One
     </option>
     <option value="" disabled>----------------</option>
     <?php foreach ($animals as $option) {
        echo "<option ";
        if ($animal == $option) {
            echo 'selected';
        }
        echo ">$option</option>"; 
     ?>
</select>

value attributes aren't required for your <option> elements in this case, since you're using the same values for the option text. (If the value attribute is omitted, the option text will be used as the value.)

Try it like this:

$animal = $mysqli->escape_string($_POST['animal']);
//PHP UPDATE database script -------->

echo '<label>Animal</label></br>
    <select name="animal">
         <option value="" disabled>Select One</option>
         <option value="" disabled>----------------</option>
         <option value="Dog" ' . ($animal == 'Dog' ? 'selected' : '') . '>Dog</option>
         <option value="Cat" ' . ($animal == 'Cat' ? 'selected' : '') . '>Cat</option>
         <option value="Bird" ' . ($animal == 'Bird' ? 'selected' : '') . '>Bird</option>  
    </select>';