简体   繁体   English

将特定数据库值加载到HTML的列表框中

[英]Load the Specific database value to the Listbox in HTML

I have developed a Sign up page in php and there is a listbox (combobox) in the registration page to choose cities.Asume a user registered with choosing New York in the listbox. 我已经在php中开发了一个Sign up页面,注册页面中有一个列表框(combobox)可以选择城市。假设一个用户在列表框中选择了New York进行注册。 Now the New York value is stored in the database.My question is I want to give the user a profile page where he can edit his last values.So when the profile page load I want to load the listbox with the New York value which get from he database. 现在纽约值存储在数据库中。我的问题是我想给用户一个个人资料页面,他可以在其中编辑他的最后一个值,所以当个人资料页面加载时,我想用纽约值加载列表框从他的数据库。 (Keep in mind I don't want to add a new value to the list box. Just want to get the previously inserted value to be selected when page loads.)How can I do this.Can some one help me. (请记住,我不想在列表框中添加新值。只想获取在页面加载时选择的先前插入的值。)我该怎么做。有人可以帮帮我。

Add a selected attribute to the <option> element that matches the data in the database. 将一个selected属性添加到与数据库中的数据匹配的<option>元素。 The easiest way to do this, generally, is to generate the options by looping over an array of all the possible values. 通常,最简单的方法是通过循环所有可能值的数组来生成选项。

I don't know how you render your cities, so I'm going to make some assumptions and leave it to you to figure out how to adapt it to your code 我不知道您是如何绘制城市的,所以我将做一些假设,然后由您自己决定如何适应您的代码

$user_city = 'New York';

$cities = [
    'Texas',
    'New York',
    'Arizona',
    'Washington'
];

echo '<select>';

foreach($cities as $city){
    echo '<option '.($city == $user_city ? 'selected' : null).'>'.$city.'</option>';
}

echo '</select>';

And also you should work with ids, instead of names as I have done in the example. 同样,您应该使用id,而不是像示例中那样使用名称。

Ok I got it working. 好吧,我知道了。 Thank you for helping. 感谢您的帮助。 Here is what I did 这就是我做的

$user_city is the value I am getting from the database. $ user_city是我从数据库中获取的值。

<select name="area" id="area" style="border:"><optgroup label="cities">
        <option value="New York"
        <?php if($user_city=='New York'){echo 'selected="selected"';} ?>>New
            York</option>
        <option value="Texas"
        <?php if($user_city =='Texas'){echo 'selected="selected"';} ?>>Texas</option>
        <option value="Arizona"
        <?php if($user_city =='Arizona'){echo 'selected="selected"';} ?>>Arizona</option>
    </optgroup>
</select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM