PHP show drop down selected based on value [closed

2020-01-30 01:32发布

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?

7条回答
甜甜的少女心
2楼-- · 2020-01-30 01:49

You search for

<option selected>CPA</option>

I recommend you to read through some HTML beginner guides.

查看更多
混吃等死
3楼-- · 2020-01-30 01:51
$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>
查看更多
闹够了就滚
4楼-- · 2020-01-30 01:55

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>
查看更多
在下西门庆
5楼-- · 2020-01-30 01:57

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.

查看更多
走好不送
6楼-- · 2020-01-30 02:01

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

?>
查看更多
我只想做你的唯一
7楼-- · 2020-01-30 02:05

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>
查看更多
登录 后发表回答