根据存储的mysql值选择选项 [英] Selecting Select Option based on stored mysql value

查看:122
本文介绍了根据存储的mysql值选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户配置文件的编辑页面。一个选项是国家,所有国家在PHP文件中列出(国家不从数据库加载)。在用户编辑个人资料页面中,我希望能够从列表中选择当前存储的选项值。

我可以这样做:

 < option value =Afghanistan<?php if($ results ['country'] =='Afghanistan')echo'selected';?> ; >阿富汗< /选项> 
< option value =Albania<?php if($ results ['country'] =='Albania')echo'selected';?> >阿尔巴尼亚< /选项>
< option value =Algeria<?php if($ results ['country'] =='Algeria')echo'selected';?> >阿尔及利亚< /选项>
< option value =美属萨摩亚<?php if($ results ['country'] =='American Samoa')echo'selected';?> >美属萨摩亚< / option>
//其他国家在这里:( ..

有没有更好的更清洁)的方式来做到这一点,而不是把所有的国家都放入数据库吗?

解决方案

迭代 $国家数组使用一个 foreach 循环,并生成选项,匹配国家值来查找选定的。





  $ countries = array(阿富汗,阿尔巴尼亚,阿尔及利亚,美属萨摩亚); 

foreach($国家为$ country){
echo< option value ='$ country';
if($ country == $ results [country]){
echoselected;
}
echo> $ country< / option> \\\
;
}

输出(对于 $ results [country] =阿尔巴尼亚

 < option value ='阿富汗'>阿富汗< / option> 
<选项值='所选的阿尔巴尼亚>阿尔巴尼亚< / option>
< option value ='阿尔及利亚'>阿尔及利亚< / option>
< option value ='美属萨摩亚'>美属萨摩亚< / option>


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?

解决方案

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>

这篇关于根据存储的mysql值选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆