Reputation: 121
On my form i am giving user access to modify his details, I am fetching details from db using application id and showing it in my form inputs with its value attribute, so user can see and modify his details if he wants to, but how can we set value in select fields that fetched from database.
here suppose variable is $country
fetched from db.
$country = 'India';
And the select fields is
<select name="usercountry" id="usercountry">
<option value="England">England</option>
<option value="South Africa">South Africa</option>
<option value="USA">USA</option>
<option value="India">India</option>
</select>
Here I want this select box to be set to $country
value automatically.
Upvotes: 1
Views: 803
Reputation: 7489
This example works form 1 to n number of countries
$userCountry = 'India';
//you get it from DB or wherever
$countries = ['India','USA'];
<select name="usercountry" id="usercountry">
<?php
foreach($countries as $country){
echo '<option value="'.$country.'" '.($userCountry == $country ? 'selected' : '').'>'.$country.'</option>';
}
?>
</select>
Upvotes: 1
Reputation: 3531
You can do it using Ternary Operator
<option <?php echo ($country == 'India')?'selected="selected"':'' ?>>
After @Scriptman Comment and suggestion I would like make it more clean
<option <?php echo ($country == 'India')?'selected':'' ?>>
Upvotes: 4
Reputation: 893
You should check the value of the $country variable to the option value.
<select name="usercountry" id="usercountry">
<option value="England" <?php if($country == 'England'){ echo "selected";}?>>England</option>
<option value="South Africa" <?php if($country == 'South Africa'){ echo "selected";}?>>South Africa</option>
<option value="USA" <?php if($country == 'USA'){ echo "selected";}?>>USA</option>
<option value="India" <?php if($country == 'India'){ echo "selected";}?>>India</option>
</select>
Upvotes: 3