从数据库中下拉选定的值

时间:2010-05-27 07:33:10

标签: php html

在编辑个人资料表单中,我想显示国家下拉列表的选定值作为保存在数据库中的值,用户也可以更改它。

4 个答案:

答案 0 :(得分:2)

echo "<select name='cmbCountry'>";
while($country = mysql_fetch_array($countries)){
    echo "<option value='".$country["id"]."'".($country["id"] == $profile["idCountry"]) ? " selected='selected'" : "".">".$country["name"]."</option>"
}
echo "</select>";

答案 1 :(得分:0)

您需要设置所选属性:

<select name="country">
  <option<?= $country == "USA" ? ' selected="selected"' : ''?>>USA</option>
  <option<?= $country == "Kanada" ? ' selected="selected"' : ''?>>Kanada</option>
  <option<?= $country == "Mexico" ? ' selected="selected"' : ''?>>Mexico</option>
</select>

<强>更新

<? $countries = array(/* Array of countries */); ?>
<select name="country">
  <? foreach($countries as $c): ?>
    <option<?= $c == $country ? ' selected="selected"' : '' ?>><?= $c ?></option>
  <? endforeach; ?>
</select>

答案 2 :(得分:0)

<select id="user" name="user[sex]" >
  <option value="male" <?php $sex == "male" ?  "selected" : '' ?>>Male</option>
  <option value="female" <?php $sex == "female" ?  "selected" : '' ?>>Female</option>
</select>

答案 3 :(得分:0)

Jens答案的稍高级版本 - 可以更轻松地添加新选项:

<?php $countries = array('USA', 'Kanada', 'Mexico'); ?>

<select name="country">
  <?php foreach ($countries as $c): ?>
    <option<?php $country == $c ? ' selected="selected"' : ''; ?>>$c</option>
  <?php endforeach; ?>
</select>