2014-10-04 92 views
1

我正在尝试编写一个由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';"); 


?> 

我怎能从getSubject数据完整的的getTitle和getSection选择后提出的?选择了最终的下拉框后,我希望它能够在菜单下面打印出所有三个选项。我一直在为此奋斗了好几个小时,不知道我的键盘可以采用多少更多的滥用。

在此先感谢您的帮助。

回答

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>"; 
} 

希望这会有所帮助。

+0

神圣的废话,谢谢一堆!它现在正在工作! – user1834616 2014-10-04 03:02:49

相关问题