1

我在下面有一个基本的 mysqli 代码,它执行查询以从数据库中选择课程编号和课程名称,并将其显示在下拉菜单中。

    $sql = "SELECT CourseId, CourseNo, CourseName FROM Course ORDER BY CourseId"; 

    $sqlstmt=$mysqli->prepare($sql);

    $sqlstmt->execute(); 

    $sqlstmt->bind_result($dbCourseId, $dbCourseNo, $dbCourseName);

    $courses = array(); // easier if you don't use generic names for data 

    $courseHTML = "";  
    $courseHTML .= '<select name="courses" id="coursesDrop" onchange="getModules();">'.PHP_EOL; 
    $courseHTML .= '<option value="">Please Select</option>'.PHP_EOL;  

    $outputcourse = ""; 
    while($sqlstmt->fetch()) 
    { 
    $course = $dbCourseId;
    $courseno = $dbCourseNo;
    $coursename = $dbCourseName; 
    $courseHTML .= "<option value='".$course."'>" . $courseno . " - " . $coursename . "</option>".PHP_EOL;  

    $outputcourse .= "<p><strong>Course:</strong> " . $courseno .  " - "  . $coursename . "</p>";

    } 

    $courseHTML .= '</select>';  

    ?>

    <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validation();">
<table>
<tr>
<th>Course: <?php echo $courseHTML; ?></th>
</tr>
</table>
<p><input id="moduleSubmit" type="submit" value="Submit Course and Module" name="moduleSubmit" /></p>
</form>

    <?php

    if (isset($_POST['moduleSubmit'])) {

    $assessmentform = "<div id='lt-container'>
<form action='".htmlentities($_SERVER['PHP_SELF'])."' method='post' id='assessmentForm'>
{$outputcourse}
</form>
</div>";

echo $assessmentform;

...

?>

现在让我们说下拉菜单包含以下这些课程:

INFO101 - Information Communication Technology
INFO102 - Computing

出于某种奇怪的原因,无论我从下拉菜单中选择哪门课程,当我单击提交按钮时,它应该在下拉菜单下输出的回声总是输出 Course Number 和 Course Name INFO102 - Computing。即使我选择了其他选项INFO101 - Information Communication Technology为什么会这样?

4

1 回答 1

1

在您的while循环中,您正在重新初始化$outputcourse每次迭代,而不是将其累积成一个长字符串。因此,它只会显示循环中获取的最后一项。

// Initialize $outputcourse outside the loop:
$outputcourse = "";
while($sqlstmt->fetch()) 
{ 
    $course = $dbCourseId;
    $courseno = $dbCourseNo;
    $coursename = $dbCourseName; 
    $courseHTML .= "<option value='".$course."'>" . $courseno . " - " . $coursename . "</option>".PHP_EOL;  

    // Match the course in $_POST with the current fetch iteration and load $outputcourse
    if (isset($_POST['courses']) && $_POST['courses'] == $course)) {
      $outputcourse = "<p><strong>Course:</strong> " . $courseno .  " - "  . $coursename . "</p>";
    }
}

现在,只有选定的课程将被加载到$outputcourse. 希望您在$assessmentform上面未显示的其他输入中包含了一些其他输入,因为现在您只是将 a 包裹<p>在 a<form>中而没有关联的输入。

于 2012-11-25T02:46:08.590 回答