如何在组合菜单中显示所选数据

时间:2018-04-04 05:31:26

标签: php

我从数据库创建动态组合,并想在编辑菜单中显示所选数据这个我的代码

<select class="form-control" id="id_prog" name="id_prog"  placeholder="Program">
    <option>-- Program --</option>
    <?php
    $query = mysql_query("select * from program order by program asc");

    while ($row = mysql_fetch_array($query)) {
        ?><option value="<?php echo $row['id_prog']; ?>"><?php echo $row['program']; ?></option><?php
    }
    ?>
</select>

1 个答案:

答案 0 :(得分:0)

根据您当前的要求,解决方案代码将如下所示:

<select class="form-control" id="id_prog" name="id_prog"  placeholder="Program">
    <option>-- Program --</option>
    <?php 
        $query=mysql_query("select * from program order by program asc");

        while($row=mysql_fetch_array($query)){
            $output = '<option value="' . $row['id_prog'] . '"';
            if($row['id_prog'] == YOUR_DESIRED_VALUE){
                $output .= ' selected="selected"';
            }
            $output .= '>' . $row['program'] . '</option>';
            echo $output;
        }
    ?>
</select>

只需将 YOUR_DESIRED_VALUE 更改为所需的值

参考:concatenation operator(.) in PHP

旁注:不要使用mysql_*函数,从PHP 5.5开始不推荐使用它们,并且在PHP 7.0中完全删除它们。请改用mysqlipdoAnd this is why you shouldn't use mysql_* functions