Reputation: 485
I have a static dropdown list in a form as below:
<select class="form-control" id="brand" name="brand">
<option value="">Please select a Brand</option>
<option value="Apple">Apple</option>
<option value="Samsung">Samsung</option>
<option value="Sony">Sony</option>
</select>
When User choose a brand, let say: Apple and Submit the form. The value "Apple" will be saved in mysql database. I have option for user to edit their form after submitting it.
When user edits the form, I know how to retrieve data from mysql and echo it out but how to make this option which contains value "Apple" as selected so that this value "Apple" will be shown up as default in stead of "Please select a brand"?
Thanks,
Upvotes: 2
Views: 3167
Reputation: 3297
Assuming the variable from your database holding this value is $brand
then you could do something like this:
<select class="form-control" id="brand" name="brand">
<option value="">Please select a Brand</option>
<option value='Apple' <?php echo $brand=='Apple'?'selected':''; ?>>Apple</option>
<option value='Samsung' <?php echo $brand=='Samsung'?'selected':''; ?>>Samsung</option>
<option value='Sony' <?php echo $brand=='Sony'?'selected':''; ?>>Sony</option>
</select>
Of course this could be done by a loop if you could get all your brands in one query. Perhaps something like this:
<select class="form-control" id="brand" name="brand">
<?php
$brands_array=array("Apple","Samsung","Sony"); // could come from DB
foreach($brands_array as $b) {
echo '<option value="',$b,'"',( $brand==$b ?' selected="selected"':'').'>',$b,'</option>';
}
?>
</select>
Hope this helps.
Credits to Ismael Miguel for his valuable comments and suggestions
Upvotes: 3
Reputation: 4275
Just connect it to mysql and check which value he checked and then just show selected in option.Use the code below for html
<select class="form-control" id="brand" name="brand">
<option value="">Please select a Brand</option>
<option value="Apple" selected>Apple</option>
<option value="Samsung">Samsung</option>
<option value="Sony">Sony</option>
</select>
In this example apple will be selected to default
Hope this helps you
Upvotes: 0
Reputation: 168
You have to set the "Selected" parameter of your option.
Example :
<option value="Apple" selected>Apple</option>
Upvotes: 1