Below I want to insert values into the database. I want to insert each student within a chosen session(exam).
Now lets say the chosen session is 34, my issue is that lets say a select box contains multiple students who are going to take this assessment like below:
<select name='addtextarea' id='studentadd' multiple='multiple' size='10'>
<option value='1'>Joe Blogs</option>
<option value='4'>Bill Kite</option>
<option value='6'>Mary Scott</option>
</select>
My question is how can I loop through each student so that it inserts the details for each student in the database so that the db table will look like this below when inserted:
SessionId StudentId
34 1
34 4
34 6
Below is the code for the insert using mysqli/php:
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : '';
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : '';
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
$insert->bind_param("ii", $sessionid, $studentid);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
Just loop the
bind_param()andexecute(), you only need to do the prepare once:To prevent inserting zeros, I would also wrap the whole of the prepared statement in something like: