I’m working on a form where users can enter multiple subjects (courses), and I need to save this data into a MySQL database using PHP. The form allows users to dynamically add multiple subjects, and each subject includes fields like course code, course name, course marks, grade, course hours, and instructor name.
However, I’m encountering an issue where only the last subject is being inserted into the database. I need help to ensure that all subjects are correctly inserted.
// Inserting each course for the student
$rowCounter = 1;
while (isset($_POST["c-code-$rowCounter"])) {
$c_code = $_POST["c-code-$rowCounter"];
$c_name = $_POST["c-name-$rowCounter"];
$c_marks = $_POST["c-marks-$rowCounter"];
$grade = $_POST["grade-$rowCounter"];
$c_hours = $_POST["c-hours-$rowCounter"];
$i_name = $_POST["i-name-$rowCounter"];
$sql = "INSERT INTO Courses (student_id, course_code, course_name, course_marks, grade, course_hours, instructor_name)
VALUES ('$student_id', '$c_code', '$c_name', '$c_marks', '$grade', '$c_hours', '$i_name')";
if ($conn->query($sql) === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$rowCounter++;
}
$conn->close();
echo "Submitted Successfull";
- I expected the form to submit all dynamically added subject rows with unique data for each row.
- I expected that each course entry would be inserted into the Courses table with the correct student_id and corresponding course details. Specifically, all rows added to the form should be processed and saved into the database, not just the last row.