dongyou26216708 2012-08-26 19:28
浏览 32
已采纳

根据存储的mysql值选择Select 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?

  • 写回答

3条回答 默认 最新

  • dos8410 2012-08-26 19:31
    关注

    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>
    ";
    }
    

    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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路