我正在使用来自数据库的值填充在php的选择输入框中,但是,当我单击“提交”按钮时,先前选择的值消失了,并且仅显示默认值。
我已经尝试了其他开发人员分享的一些帖子,但是我的似乎无法正常工作。
<select name="pickup">
echo "<option value='area'>Select where you want the cab to pick you from</option>";
<?php $sql1 = "SELECT area FROM places ORDER BY area ASC;";
$resultSet1 = mysqli_query($conn, $sql1);
while($rows1 = mysqli_fetch_assoc($resultSet1)) {
$area1 = $rows1['area'];
echo "<option value='$area1'>$area1</option>";
}?>
我没有任何错误,只是不保留先前选择的值。
答案 0 :(得分:2)
尝试以下代码片段,可能会解决您的查询-
<?php
@session_start(); /*This line would be on top of the page*/
if(isset($_POST["demo"])) {
$_SESSION["selected_val"] = $_POST["demo"];
}else{
$_SESSION["selected_val"] = "";
}
echo "<select name="demo" > <option value='area'>Select where you want the cab to pick you from</option>";
$sql1 = "SELECT area FROM places ORDER BY area ASC;";
$resultSet1 = mysqli_query($conn, $sql1);
while($rows1 = mysqli_fetch_assoc($resultSet1)) {
$area1 = $rows1['area'];
$selected = ($area1 == $_SESSION["selected_val"]) ? 'selected' : "" ;
echo "<option value='$area1' ".$selected.">$area1</option>";
}
echo "</select>";
?>
答案 1 :(得分:0)
在会话中设置选定的选项值,然后在重载后匹配选项和会话值并设置选择