仅在插入一行时才显示成功消息

时间:2013-01-11 12:46:45

标签: php mysqli

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

以下是代码:

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



        ?>

2 个答案:

答案 0 :(得分: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"));
}

答案 1 :(得分:0)

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

似乎更有可能是因为你试图输出几个json格式化的字符串,无论在另一端收到它们的是什么,实际上是导致问题的部分,因为它没有正确识别它。最好将所有消息推送到循环外定义的数组中,然后在循环完成后回显一次。如果在其余成功的情况下,许多特定查询失败,它还会为您提供更详细的信息。