开发者

dropdown selected value from database [closed]

开发者 https://www.devze.com 2023-01-01 00:36 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be 开发者_StackOverflow社区reasonably answered in its curr
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be 开发者_StackOverflow社区reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

In edit profile form I want to display selected value of Country dropdown list as value saved in db and user can change that also.


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


<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>


you need to set the selected attribute:

<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>

UPDATE

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


slightly advanced version of Jens' answer - makes it easier to add new options:

<?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>
0

精彩评论

暂无评论...
验证码 换一张
取 消