无法在for循环中执行查询

时间:2013-09-25 18:55:46

标签: php mysqli

嗨,所以我知道这是以前似乎已经回答过的事情,但我尝试过的任何事都没有奏效。基本上我要做的是调用一个插入一些数据的存储过程,并返回刚刚插入的auto_increment的id。然后该声明被关闭,我保留了id。

然后有趣的部分发生了。我进入一个循环,对于循环的每个实例,我需要调用另一个插入一些数据的存储过程,并返回最后一个auto_increment的id。使用该ID我将继续做更多的事情。但是,现在它在循环中失败了。它第一次执行没有问题,然后准备下一次绕过它给我错误Commands out of sync; you can't run this command now

我真的试图以某种方式释放第一次使用stmt-> free()的结果,但这不起作用,或者释放mysqli2连接,但我做的一切都没有奏效在此刻。任何提示或提示都会非常感激!

$insert_questionnaire_sql = "CALL insert_questionnaire_info(?, ?, ?, ?, ?, ?, ?)";

$questionnaire_insert_stmt = $mysqli->prepare($insert_questionnaire_sql);
$questionnaire_insert_stmt->bind_param("ssisiis", $meta[0], $meta[4], $length_of_questions, $user, $meta[2], $meta[3], $meta[1]);

//execute the statement
$success = $questionnaire_insert_stmt->execute();

$qn_id = -1;
//bind the id of the questionnaire that was just inserted
$questionnaire_insert_stmt->bind_result($qn_id);

//fetch the id
$questionnaire_insert_stmt->fetch();

//close the statement
$questionnaire_insert_stmt->close();


//next we insert each question into the database
$i = 0;
for($i; $i < count($Questions); $i++){
    //only if the question has been submitted
    if($Questions[$i]->submitted){
        //prepare the statement
        $insert_question_sql = "CALL insert_question_info(?, ?, ?, ?, ?, ?, ?)";
        $question_insert_stmt = $mysqli2->prepare($insert_question_sql) or die ($mysqli2->error);

        $type = -1;
        $width = -1;
        $height = -1;
        //count the number of answers
        $numAnswers = countNotDeletedAnswers($Questions[$i]);
        $text = $Questions[$i]->text;
        //figure out what kind of thing this is
        if($Questions[$i]->instruction == true){
            $type = 2;
        }
        else if($Questions[$i]->image == true){
            $type = 3;
            $width = $Questions[$i]->width;
            $height = $Questions[$i]->height;
            //if we have an image we want to put the path as the text
            $text = $Questions[$i]->path;
        }
        else{
            $type = 1;
        }

        //bind the params
        $question_insert_stmt->bind_param("isiisii", $qn_id, $text, $type, $numAnswers, $user, $width, $height);
        //execute
        $success = $question_insert_stmt->execute() or die ($mysqli2->error);
        //bind the id of the questionnaire that was just inserted
        $q_id = -1;
        $question_insert_stmt->bind_result($q_id);
        //fetch the id
        $data = $question_insert_stmt->fetch();

        //close the statement
        $question_insert_stmt->close();

    }

}

1 个答案:

答案 0 :(得分:1)

CALL - 查询获取其他结果集,如docs中所述。在这样的查询之后尝试循环throght其他结果集并释放它们,使用类似这样的东西:

function cleanUp(mysqli_stmt $stmt)
    {
        do
            {
                // $stmt->store_result();
                $stmt->free_result();
            }
        while($stmt->more_results() && $stmt->next_result());
    }

否则,如果您的过程返回任何结果集,那么您将收到此错误,而该free()正确无法{/ p}}。