我创建了一个网页,该网页需要填充MySQL数据库中的下拉列表。到目前为止很容易。我想有多个下拉菜单,具体取决于彼此。换句话说,我希望第一个下拉列表更改第二个的值,依此类推。我用示例代码尝试了它,并且效果很好。当我用实际表尝试时,第二个下拉列表并不是基于第一个下拉列表进行过滤的。它在第一个下拉列表(课程)中获取值并执行准备好的语句。但这会带回表中的所有模块,而不仅仅是选定课程的模块。 我必须在其中输入一个错字,因为我已经通过示例表完成了它,并且工作正常。另外,我直接尝试了SQL,它也可以工作。我准备好的陈述可以吗? “ connect_db.php”页面也可以与我的示例表正常工作。 我的代码是
<?php
$page_title='My Dropdown Test';
include('header.html');
?>
<script>
function reload(form){
var val=form.course.options[form.course.options.selectedIndex].value;
self.location='CourseModuleDropDown.php?course=' + val ;
}
</script>
<?php
require('../../connect_db.php');
if($dbc->connect_error) {
die("Database connection failed");
}
$course=$_GET['course']; // Check that course is not empty
if(strlen($course) <= 0){
echo "Data Error";
exit;
}
// ### Getting the data from Mysql table for course drop down ### //
$query2="SELECT DISTINCT name,CourseCode FROM courses order by name";
echo "<form method=post name=f1 action='next_page.php'>";
echo "<select name='course' onchange=\"reload(this.form)\">
<option value=''>Select one</option>";
if($stmt = $dbc->query("$query2")){
while ($row2 = $stmt->fetch_assoc()) {
if($row2['CourseCode']==$course){
echo "<option selected value='$row2[CourseCode]'>$row2[name]</option>";
}else{
echo "<option value='$row2[CourseCode]'>$row2[name]</option>";
}
}
}else{
echo $dbc->error;
}
echo "</select>";
// ### End Course drop down list ### //
// ### Getting the data from Mysql table for module drop down (based on selected course)### //
echo "### $course ~ Length => ".strlen($course)." ###</br></br>"; // this was just for testing
echo "<select name='module'><option value=''>Select one</option>";
if(isset($course) and strlen($course) > 0){
if($stmt = $dbc->prepare("SELECT DISTINCT ModuleCode FROM modules where CourseCode=? order by ModuleCode")){
$stmt->bind_param('i',$course);
$stmt->execute();
$result = $stmt->get_result();
while ($row1 = $result->fetch_assoc()) {
echo "<option value='$row1[ModuleCode]'>$row1[ModuleCode]</option>";
}
}else{
echo $dbc->error;
}
}else{
$query="SELECT DISTINCT ModuleCode FROM modules order by ModuleCode";
if($stmt = $dbc->query("$query")){
while ($row1 = $stmt->fetch_assoc()) {
echo "<option value='$row1[ModuleCode]'>$row1[ModuleCode]</option>";
}
}else{
echo $dbc->error;
}
}
echo "</select>";
// ### End Module drop down list ### //
echo "<input type=submit value='Submit'></form>";
?>
<?php include('footer.html');?>