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>
精彩评论