doubi7739 2017-03-10 12:20
浏览 45
已采纳

PHP - 保存提交后选择选项值

I have a drop down menu which lists the associated 'IDs' from the mysql database:

<fieldset>
<legend><strong>Change ID:</strong></legend>
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "change_management";

$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$query3 = "SELECT `change_id` FROM `change_request_tbl` WHERE (approval_disposition LIKE 'Requires Editing')";
$result3 = mysqli_query($connect,$query3);
?>

<select required name="change_id">
<option value="">Please specify...
<?php
while ($roww = mysqli_fetch_array($result3))
{
echo "<option value='".$roww['change_id']."'>".$roww['change_id']."</option>";
}
?>
</select>
<input type="submit" name="get" value="Get Details" class="btn">
</fieldset><br><br><br>

When the user clicks "Get Details" the dropdown reverts back to "Please specify". I have found many examples of how to save the value after submission, but none seem to be applicable to my code as I am fetching values from the database. Is there anyway to save the last inputted values in this current format?

  • 写回答

1条回答 默认 最新

  • dongxiong5546 2017-03-10 12:26
    关注

    When the user submits the form, the form value change_id has the value you're looking for. So when populating your option elements you can check if any of them match what was submitted and set it to be selected. Something like this:

    if (isset($_POST['change_id']) && $roww['change_id'] == $_POST['change_id']) {
        echo "<option selected value='".$roww['change_id']."'>".$roww['change_id']."</option>";
    } else {
        echo "<option value='".$roww['change_id']."'>".$roww['change_id']."</option>";
    }
    

    Or if you want it all on one line (using the ternary conditional operator):

    echo "<option ".((isset($_POST['change_id']) && $roww['change_id'] == $_POST['change_id']) ? "selected" : "")." value='".$roww['change_id']."'>".$roww['change_id']."</option>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题