0

为什么我只在数据库中插入一行,它会显示成功消息,但是如果我在数据库中插入多行,那么它不会显示成功消息?

下面是代码:

$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();



        ?>
4

2 回答 2

1

您需要在每次查询后未输出所有查询后移动状态消息。故障检测也是错误的。

$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"));
}
于 2013-01-11T12:59:26.033 回答
0

您确定没有输出吗?(我假设没有输出,因为您没有提到您收到了错误消息)

似乎更有可能是因为您正在尝试输出几个 json 格式的字符串,所以在另一端接收它们的任何内容实际上都是由于无法正确识别而导致问题的部分。最好将所有消息推送到循环外部定义的数组中,然后在循环完成后回显一次。如果多个查询中的一个特定查询失败而其余查询成功,它还会为您提供更详细的信息。

于 2013-01-11T12:55:43.107 回答