PHP 显示根据值选择的下拉列表

2021-12-19 00:00:00 drop-down-menu select php

我想显示为来自数据库的某些值选择的下拉列表.

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>

在 PHP/Mysql 中从数据库中读取一个值,比如说CPA",我如何显示这个选项被选中?

Reading a value from database in PHP/Mysql, lets say "CPA", how do I show this option selected?

推荐答案

您需要使用 HTML 中的 selected 属性.

You need to use the selected attribute in HTML.

例如,如果您从数据库中获得的值被分配给一个变量,例如 $val,

If for example the value you got from the database is assigned to a variable say $val,

然后你可以这样做:

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

相关文章