Selecting Select Option based on stored mysql valu

2019-08-28 22:44发布

I have an edit page for user profiles. One option is 'Country' with all the countries listed in the php file (countries are not loaded from database). On the user edit profile page I want to be able to select the currently stored option value from the list.

I could do this:

<option value="Afghanistan" <?php if ($results['country'] == 'Afghanistan') echo 'selected';?> >Afghanistan</option>
<option value="Albania" <?php if ($results['country'] == 'Albania') echo 'selected';?> >Albania</option>
<option value="Algeria" <?php if ($results['country'] == 'Algeria') echo 'selected';?> >Algeria</option>
<option value="American Samoa" <?php if ($results['country'] == 'American Samoa') echo 'selected';?> >American Samoa</option>
 // The rest of the countries here :(..

Is there a better (cleaner) way to do this without putting all the countries into the db?

标签: php mysql forms
3条回答
我只想做你的唯一
2楼-- · 2019-08-28 23:15

In addition to the other answers if you can't store the countries in a DB you may consider storing them in a text file. Read them in and iterate over them. This will make it easier to add new countries without changing code. Just a thought.

查看更多
Emotional °昔
3楼-- · 2019-08-28 23:18

If I understand what you want right, I suggest using a foreach loop:

$countries = array(
    "Afghanistan",
    "Albania",
    "Algeria",
    "American Samoa"
    // ...
);

foreach($countries as $country) {
    echo '<option value="'.$country.'"';
    if($country == $results['country']) {
        echo ' selected="selected"';
    }
    echo '>'.$country.'</option>';
}
查看更多
祖国的老花朵
4楼-- · 2019-08-28 23:41

There is, iterate a $countries array using a foreach loop, and generate the options, match against the country value to find the selected.

Example:

$countries = array("Afghanistan", "Albania", "Algeria", "American Samoa");

foreach ($countries as $country) {
    echo "<option value='$country'";
    if ($country == $results["country"]) {
        echo " selected";
    }
    echo ">$country</option>\n";
}

Outputs (for $results["country"] = "Albania"):

<option value='Afghanistan'>Afghanistan</option>
<option value='Albania' selected>Albania</option>
<option value='Algeria'>Algeria</option>
<option value='American Samoa'>American Samoa</option>
查看更多
登录 后发表回答