I have a basic mysqli code below where it performs a query to select Course number and Course Name from database and display it in a drop down menu.
$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;
...
?>
Now lets say the drop down menu contains these courses below:
INFO101 - Information Communication Technology
INFO102 - Computing
For some strange reason no matter which course I choose from the drop down menu, when I click on the the submit button, the echo it is suppose to output underneath the drop down menu always outputs the Course Number and Course Name INFO102 - Computing. This is even though I selected the other option INFO101 - Information Communication Technology Why is this happening?
In your
whileloop, you are reinitializing$outputcourseon each iteration, rather than accumulating it into a long string. It therefore would only ever show the last item fetched in your loop.Now, only the selected course will be loaded into
$outputcourse. Hopefully you have included some other inputs in your$assessmentformwhich are not shown above, because as it is now you have just wrapped a<p>inside a<form>with no associated inputs.