发布后,从下拉列表中保留一个值

时间:2014-10-04 01:58:34

标签: php session post drop-down-menu

我正在尝试编写一个由3部分组成的下拉列表选择菜单。第二个下拉列表依赖于第一个列表中的数据,第三个下拉列表依赖于来自第二个下拉列表的数据。我已尝试使用post来执行此操作,但每次提交表单时,它都会从上一个下方框中删除数据,如果我尝试使用会话变量来存储数据,那么在表单提交时也会重置它。

这是我的代码:

    //get a list of course subjects from the database
$subjects = mysqli_query($con,"SELECT subject FROM db.course;");
echo "<select name='getSubject' onchange='this.form.submit()'>";
echo '<option value="" style="display:none;" ></option>';
while ($row=mysqli_fetch_array($subjects) )
{
   echo "<option value='" . $row['subject'] . "' >". $row['subject'] ."</option>"; //creates drop down list of subjects

}
echo "</select> &nbsp;";

$selectedSubject = $_POST['getSubject'];
echo $selectedSubject;

//get a list of course titles from the database, based on subject chosen
$courses = mysqli_query($con,"SELECT title FROM db.course WHERE subject = '$selectedSubject';");
echo "<select name = 'getTitle' style='width:500px;' onchange='this.form.submit()'>";
echo '<option value="" style="display:none;"></option>';
while ($row=mysqli_fetch_array($courses) )
{
   echo "<option value='" . $row['title'] . "' >". $row['title'] ."</option>"; //creates a drop down list of course titles

}
echo "</select> &nbsp;";

$selectedTitle = $_POST['getTitle'];
echo "$selectedTitle";


//get a list of section numbers from the database, based on course chosen
$sections = mysqli_query($con,"SELECT section FROM db.course WHERE title = '$selectedTitle';");
echo "<select name = 'getSection' style='width:200px;' onchange='this.form.submit()'>";
echo '<option value="" style="display:none;"></option>';
while ($row=mysqli_fetch_array($sections) )
{
   echo "<option value='" . $row['section'] . "' >". $row['section'] ."</option>"; //creates drop down list of course sections

   }
echo "</select>";

$selectedSection = $_POST['getSection'];


$course = mysqli_query($con,"SELECT title, subject, section FROM db.course WHERE subject = '$selectedSubject';");


?>

从getTitle和getSection中选择后,如何保持getSubject中的数据不变?在选择了最后一个下拉框之后,我希望它能够在菜单下方打印所有三个选项。我现在已经在这几个小时内苦苦挣扎了,我不确定我的键盘会有多少滥用。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在打印选项的循环内添加一个条件,如果这是在提交时选择的选项,则使用selected参数。

while ($row=mysqli_fetch_array($subjects)) {
   if($_POST['getSubject'] == $row['subject']) $s = " selected"; else $s = "";
   echo "<option value='{$row['subject']}'$s>{$row['subject']}</option>";
}

while ($row=mysqli_fetch_array($courses)) {
   if($_POST['getTitle'] == $row['title']) $s = " selected"; else $s = "";
   echo "<option value='{$row['title']}'$s>{$row['title']}</option>";
}

while ($row=mysqli_fetch_array($sections)) {
   if($_POST['getSection'] == $row['section']) $s = " selected"; else $s = "";
   echo "<option value='{$row['section']}'$s>{$row['section']}</option>";
}

希望这有帮助。