This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,
visit the help center.
Closed 6 years ago.
I want to show a drop down selected for some value which is coming from database.
<select name="plans">
<option>MAP</option>
<option>CP</option>
<option>CPA</option>
<option>CPF</option>
</select>
Reading a value from database in PHP/Mysql, lets say "CPA", how do I show this option selected?
You need to use the selected
attribute in HTML
.
If for example the value you got from the database is assigned to a variable say $val
,
Then you can do it as follows :
<select name="plans">
<option <?php echo ($val == 'MAP')?"selected":"" ?> >MAP</option>
<option <?php echo ($val == 'CP')?"selected":"" ?> >CP</option>
<option <?php echo ($val == 'CPA')?"selected":"" ?> >CPA</option>
<option <?php echo ($val == 'CPF')?"selected":"" ?> >CPF</option>
</select>
You search for
<option selected>CPA</option>
I recommend you to read through some HTML beginner guides.
$row->will contain the name of plans after query execution
<select name="plans">
<option value="MAP" <?php if($row['plans']=="MAP") echo selected;?>>MAP</option>
<option value="CP" <?php if($row['plans']=="CP") echo selected;?>>CP</option>
<option value="CPA">CPA</option>
<option value="CPF">CPF</option>
</select>
Try like this
<select name="plans">
<option <?php echo ($value == "MAP")?"selected":"" ?> >MAP</option>
<option <?php echo ($value == "CP")?"selected":"" ?> >CP</option>
<option <?php echo ($value == "CPA")?"selected":"" ?> >CPA</option>
<option <?php echo ($value == "CPF")?"selected":"" ?> >CPF</option>
</select>
You need to use the selected
attribute in the <option>
HTML tag.
Full code:
<?php
$dbValue = 'CPA';
$options = array
(
'MAP' => 'MAP',
'CP' => 'CP',
'CPA' => 'CPA',
'CPF' => 'CPF'
);
echo '<select name="plans">';
foreach ($options as $value => $option)
{
$selected = $value == $dbValue ? 'selected="selected"' : '';
echo "<option {$selected} value=\"{$value}\">{$option}</option>";
}
echo '</select>';
?>
Put selected in for the option you want to be selected.
Like:
<select name="plans">
<option>MAP</option>
<option>CP</option>
<option selected>CPA</option>
<option>CPF</option>
</select>
When you build the above list, for each option you check whether it is the one in the database. And when it is, you add selected.
Try this as an example.
//$val = Value from database;
<select name="plans">
<option <?php if(isset($val) && $val=="1") {?> selected="selected"<?php } ?> value="1" >MAP</option>
<option <?php if(isset($val) && $val=="2") {?> selected="selected"<?php } ?> value="2" >CP</option>
<option <?php if(isset($val) && $val=="3") {?> selected="selected"<?php } ?> value="3" >CPA</option>
</select>