在选择框中保留选定的值

时间:2018-01-29 11:41:52

标签: php mysql drop-down-menu

如何在从数据库动态填充的选择框中保留我选择的选项。我见过很多答案,但大部分是静态值。这是我的代码,

  <select name="batchnumber" class="form-control"  id="batchno" required>   

         <option value="">select batch number</option>                 
       <?php 
            $sql = mysql_query("SELECT DISTINCT rpp_regn_bulkbatch_no,rpp_id FROM tbl_regn_prescribed_parameters where rpp_regn_bulkbatch_no  != 0");
                  while ($row = mysql_fetch_assoc($sql)){   

           echo "<option value=" . $row['rpp_regn_bulkbatch_no'] . ">" . $row['rpp_regn_bulkbatch_no'] . "</option>";       
              }
        ?>
        </select>

3 个答案:

答案 0 :(得分:1)

您好我们可以通过添加if条件

来完成此操作
while ($row = mysql_fetch_assoc($sql))
{   
    if($_REQUEST['batchnumber'] == $row['rpp_regn_bulkbatch_no'])
    {
        echo "<option selected value=" . $row['rpp_regn_bulkbatch_no'] . ">" . $row['rpp_regn_bulkbatch_no'] . "</option>";       
    }
    else
    {
        echo "<option value=" . $row['rpp_regn_bulkbatch_no'] . ">" . $row['rpp_regn_bulkbatch_no'] . "</option>";  
    }

}

但是尝试使用mysqli_ *函数而不是mysql _ *

答案 1 :(得分:1)

html中的选定属性可以帮助你。

您所要做的就是检查行的rpp_regn_bulkbatch_no是否等于当前选择。

$currently_selected_rpp_regn_bulkbatch_no=123;

while ($row = mysql_fetch_assoc($sql)){   

$selected=$row['rpp_regn_bulkbatch_no']==$currently_selected_rpp_regn_bulkbatch_no?("selected"):("");

echo "<option $selected value=" . $row['rpp_regn_bulkbatch_no'] . ">" . $row['rpp_regn_bulkbatch_no'] . "</option>";

}

所以基本上将当前rpp_regn_bulkbatch_no转换为变量并检查行的值是否等于每行中的当前值。如果匹配,请将“selected”prop添加到选项。

答案 2 :(得分:1)

<select name="batchnumber" class="form-control"  id="batchno" required>          
   <?php 
   $sql = mysql_query("SELECT DISTINCT rpp_regn_bulkbatch_no,rpp_id FROM tbl_regn_prescribed_parameters where rpp_regn_bulkbatch_no  != 0");
   $selected="";
   while ($row = mysql_fetch_assoc($sql))
   {  
     $selected=$_POST['batchnumber']==$row['rpp_regn_bulkbatch_no']?"selected":""; 
     echp "<option value=".$row['rpp_regn_bulkbatch_no']." ".$selected.">".$row['rpp_regn_bulkbatch_no']."</option>";   

   }
   ?></select>

表单方法,无论是GET还是POST