SET selected in the select tag

时间:2016-11-12 05:52:44

标签: php mysql

<select class="form-control" name="Church" id="Church">
  <option>Church List</option>
    <?php 
         $select_church = mysql_query("SELECT * FROM tblchurchs");
         while($get_detail = mysql_fetch_array($select_church)){
          echo'<option value="'.$get_detail['AChurchID'].'">'.$get_detail['ChurchName']." - ".$get_detail['Address'].'</option>';
        }
    ?>
</select>

This is Edit.php

This is the result of that code enter image description here but i want is. after getting the data from the database. it will automatically selected the value of the option base on the database data.

2 个答案:

答案 0 :(得分:0)

Suppose the query result returned from tblchurchs contains a field Selected which is either set to 1 or 0. If it is set to 1 then you have to select that option in your drop-down list, and if it is set to 0, it is not selected.

<select class="form-control" name="Church" id="Church">
  <option>Church List</option>
    <?php 
         $select_church = mysql_query("SELECT * FROM tblchurchs");
         while($get_detail = mysql_fetch_array($select_church)){
          echo'<option value="'.$get_detail['AChurchID'].'"';
          if($get_detail['Selected'] == 1)
            {
                echo ' selected="selected"';
            }
          echo '>'.$get_detail['ChurchName']." - ".$get_detail['Address'].'</option>';
        }
    ?>
</select>

答案 1 :(得分:0)

选择所选选项。 首先,您必须将从数据库获取的选定数据保存到变量,然后使用if循环,您可以执行此操作。

<?php 
$AChurchID=1; // this is your already selected value that is in db .
?>
<select class="form-control" name="Church" id="Church">
  <option>Church List</option>
    <?php 
         $select_church = mysql_query("SELECT * FROM tblchurchs");
         while($get_detail = mysql_fetch_array($select_church)){
            $sel="";
            if($AChurchID==$get_detail['AChurchID']){
            $sel="selected";
        }
          echo'<option value="'.$get_detail['AChurchID'].'" '.$sel.'>'.$get_detail['ChurchName']." - ".$get_detail['Address'].'</option>';
        }
    ?>

这适用于您的情况。这种情况很好用。请试试。