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 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟