如何使用php从已经保存在数据库中的下拉列表中选择一些内容


how to select something from the drop down already saved in a database using php?

我有以下国家的下拉列表:

<select name="country">
    <option value="">Country...</option>
    <option value="Afganistan">Afghanistan</option>
    <option value="Albania">Albania</option>
    <option value="Algeria">Algeria</option>
    <!-- Removed several options as they are not needed for question -->
    <option value="Zaire">Zaire</option>
    <option value="Zambia">Zambia</option>
    <option value="Zimbabwe">Zimbabwe</option>
</select>

当用户编辑其配置文件时,我希望默认情况下选择用户(在数据库中)选择的国家/地区。

示例

当用户注册时,选择了Egypt。当用户编辑其配置文件时,我希望此下拉列表默认选择Egypt(直到更改为止)。

只需将selected属性添加到用户创建帐户时选择的option即可。

基本理念

Foreach

<?php
$country_list = '<select name="country">';
$selected_country = $user_info['country'];
foreach($countries as $country){
 $is_selected = ($country===$selected_country);
 $country_list .= '<option value="'.$country.'"'.($is_selected ? ' selected' : '').'>$country</option>';
}
$country_list .= '</select>';

While

<?php
...
$country_list = '<select name="country">';
$selected_country = $user_info['country'];
$stmt->bind_result($country);
while($mysqli->fetch()){
 $is_selected = ($country===$selected_country);
 $country_list .= '<option value="'.$country.'"'.($is_selected ? ' selected' : '').'>$country</option>';
}
$country_list .= '</select>';

注意:虽然它会占用更多的资源,但我建议至少使用一系列国家,但最好将这些国家存储在数据库中。数据库的原因是,如果你更改了一个国家的名称(例如,苏联更改为俄罗斯),你就不必为每个用户更新它(因为他们会链接到countries表中的id)。我建议使用数据库或数组,因为您迟早会在某个时间点更改option列表的标记,并且将列表放在数组中可以更改单行,而不是为列出的每个国家更改一次

Html语法如下:

<option value="AAAA" selected>label</option>

因此,在PHP中,从DB加载您的值和您选择的值,当您在循环中打印它们时,如果当前打印的值是所选的值,则只返回一个"所选"。

从数据库值中定义一个变量。将整个<select>标记存储为一个变量。查找选定的选项值并将其替换为选定的属性。

$country_selected_value;
// defined from database
$country_select = '<select name="country">...</select>';
// ... represents your options
$value_search = 'value="'.country_selected_value.'"';
// what to look for in the select
echo str_replace($value_search , $value_search.'" selected="selected"', $country_select);
// displaying the select field with the selected option

如果你需要帮助从数据库中获取数据,那么SO上已经有很多这样的主题了。