I cannot seem to figure it out but I am getting an error in my php/mysqli stating:
Warning: Invalid argument supplied for foreach() in
/…/ on line 28
My question is that how can the above warning be fixed so that I can loop over the insert to be able to provide all of the inserts into the db:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
// connect to the database
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$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
}
foreach($studentid as $id)
{
$insert->bind_param("ii", $sessionid, $id);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
}
$insert->close();
$query = "SELECT ss.SessionId, SessionName, StudentId
FROM
Student_Session ss
INNER JOIN Session s ON
ss.SessionId = s.SessionId
WHERE ss.SessionId = ? AND StudentId = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("ii", $sessionid, $studentid);
// execute query
$stmt->execute();
// get result and assign variables (prefix with db)
$stmt->bind_result($dbSessionId, $dbSessionName, $dbStudentId);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();
//fetch the results
$stmt->fetch();
if ($numrows == 1){
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"));
}
?>
Your conditional where
$studentidis set can set the value to an empty string. You should probably have some conditional in there to not even attempt to prepare as statement and insert data in such a case.