Reputation: 741
How come when I insert just one row into the database, it displays the success mesage, but if I insert multiple rows into db, then it does not display success message?
Below is code:
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array();
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : array();
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql)) {
// Handle errors with prepare operation here
}
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
$insert->execute();
if ($insert->errno) {
echo json_encode(array('errorflag'=>true,'msg'=>"An error has occured, Students have not been added into the Assessment"));
}else{
echo json_encode(array('errorflag'=>false,'msg'=>"Students have been successfully added into the Assessment"));
}
}
$insert->close();
?>
Upvotes: 0
Views: 609
Reputation: 1115
You need to move status messages after all queries not output after each query. Also failure detection was wrong.
$studentid = (isset($_POST['addtextarea'])) ? $_POST['addtextarea'] : array();
$sessionid = (isset($_POST['Idcurrent'])) ? $_POST['Idcurrent'] : array();
$insertsql = "
INSERT INTO Student_Session
(SessionId, StudentId)
VALUES
(?, ?)
";
if (!$insert = $mysqli->prepare($insertsql))
{
// Handle errors with prepare operation here
}
$success = true;
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
if($insert->execute() === false)
{
$success = false;
}
}
$insert->close();
if($success)
{
echo json_encode(array('errorflag'=>false,'msg'=>"Students have been successfully added into the Assessment"));
}
else
{
echo json_encode(array('errorflag'=>true,'msg'=>"An error has occured, Students have not been added into the Assessment"));
}
Upvotes: 1
Reputation: 526
Are you definitely sure that you are getting no output? (I assume no output because you didn't mention that you were getting the error message instead)
It seems more likely that because you are trying to output several json formatted strings that whatever is receieving them on the other end is actually the part causing the problems by not recognising it properly. It might be better to push all messages into an array defined outside of the loop then echoing that just the once after the loop has completed. It would also give you more granular information if a specific query out of many failed when the rest succeeded.
Upvotes: 0