如何从数据库中获取数据以在php中选择标记

时间:2017-02-27 11:06:07

标签: php html mysql

one of the answers from this question

中找到了这个

我想问一下,这有什么问题吗? 我将var_dump列为正确的列显示BSIT。 但是,如果用户是BSIT,那么我无法获得BSCS选择的选项。

<select class="form-control" name="course">
    <?php
        if ($row['course'] == 'BSIT') {

        echo "<option selected>BSIT</option>";
        echo "<option>BSCS</option>";

        } else {
        echo "<option selected>BSCS</option>";
        echo "<option>BSIT</option>";
    }
    ?>
</select>    

5 个答案:

答案 0 :(得分:1)

只需使用此代码

<?php
// $row['course'] = 'BSCS';
 ?>
<select class="form-control" name="course" >
 <option  <?php if($row['course'] == 'BSIT' ) { echo "selected='selected'"; }?>  >BSIT</option>
<option <?php if($row['course'] == 'BSCS' ) { echo "selected='selected'"; }?> >BSCS</option>
</select>

无需检查条件并更改$ row [&#39;当然&#39;] =&#39; BSIT&#39 ;;为你测试

答案 1 :(得分:1)

实际上你应该为$ row = ['course']

声明变量
 <select class="form-control" name="course">
    <?php
        if ($course == 'Bachelor of Science in Information Technology') {

        echo "<option value='Bachelor of Science in Information Technology' selected>Bachelor of Science in Information Technology</option>";
        echo "<option value='Bachelor of Science in Computer Science'>Bachelor of Science in Computer Science</option>";

    } else {
        echo "<option value='Bachelor of Science in Computer Science' selected>Bachelor of Science in Computer Science</option>";
        echo "<option value='Bachelor of Science in Information Technology'>Bachelor of Science in Information Technology</option>";
    }
    ?>
</select>

我已经测试过了。它在工作

答案 2 :(得分:0)

您在这里错过了select标记。同时为选项指定值以将其检索回来

echo "<select>";
        if ($row['course'] == 'BSIT') {

            echo "<option selected>BSIT</option>";
            echo "<option>BSCS</option>";

        } else {
            echo "<option selected>BSCS</option>";
            echo "<option>BSIT</option>";
    }
    echo "</select>";

每次最佳做法是将内容存储在变量中并在

之后回显它,而不是使用echo
<?php
    $msg="";
//retrieve the $row['course'] from the DB. Fetch the result and store 
        if ($row['course'] == 'BSIT') {

            $msg.= "<option selected>BSIT</option>";
            $msg.= "<option>BSCS</option>";

        } else {
            $msg.= "<option selected>BSCS</option>";
            $msg.= "<option>BSIT</option>";
    }

?>
<select class="form-control" name="course" >
<?php echo $msg;?>
</select>

答案 3 :(得分:0)

只需切换大括号的内容即可。然后当$ row [&#39; course&#39;]持有&BSAN&#39;时,BSCS将显示为已选中。和BSCS做其他事情。

答案 4 :(得分:0)

我认为这会对你有所帮助。请试试这个

<select class="form-control" name="course" value="<?php echo $row['course']; ?>">
   <option value="BSIT">BSIT</option>
   <option value="BSCS">BSCS</option>
</select>

该值将显示在下拉框中。