0

I have a working php/mysqli code below where it inserts questions and answers successfully:

$i = 0;
$c = count($_POST['numQuestion']);

$questionsql = "INSERT INTO Question (SessionId, QuestionId, QuestionContent) 
                    VALUES (?, ?, ?)";



        $sessid =  $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');

            if (!$insert = $mysqli->prepare($questionsql)) {
      // Handle errors with prepare operation here
    } else{

for($i = 0;  $i < $c; $i++ ){      


$results = $_POST['value'];
foreach($results as $id => $value) {
$answer = $value;


        $insert->bind_param("sis", $sessid, $id, $_POST['questionText'][$i]);

        $insert->execute();

        if ($insert->errno) {
          // Handle query error here
        }

       $lastID = $insert->insert_id;

       $insert->close();

        foreach($value as $answer) {

         $answersql = "INSERT INTO Answer (SessionId, QuestionId, Answer) 
    VALUES (?, ?, ?)";

      if (!$insertanswer = $mysqli->prepare($answersql)) {
      // Handle errors with prepare operation here
    }  

    $insertanswer->bind_param("sis", $sessid, $lastID, $answer);

        $insertanswer->execute();

        if ($insertanswer->errno) {
          // Handle query error here
        }

        $insertanswer->close();

}
}

}

}

But a trouble I have been having even before getting the above code to work is that I have 2 additional SELECT queries which I need include in the code above. The queries are known as $replystmt and $optionstmt. The problem though is that if I include those queries in the php/mysqli code above, I keep receiving these errors:

Warning: mysqli_stmt::execute(): (HY000/2014): Commands out of sync; you can't run this command now in /insertQuestion.php on line 236 241:

Commands out of sync; you can't run this command now Fatal error: Cannot break/continue 2 levels in /insertQuestion.php on line 242

Now the full code is below, my question is that what do I need to change in my code in order for the errors to be removed and the code to work?

Below is the full php/mysqli code:

$replyquery = "SELECT ReplyId FROM Reply WHERE (ReplyType = ?)";

if (!$replystmt = $mysqli->prepare($replyquery)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}

$optionquery = "SELECT OptionId FROM Option_Table WHERE (OptionType = ?)";

if (!$optionstmt = $mysqli->prepare($optionquery)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}

// Prepare your statements ahead of time
$questionsql = "INSERT INTO Question (SessionId, QuestionId, QuestionContent, NoofAnswers, ReplyId, QuestionMarks, OptionId) 
VALUES (?, ?, ?, ?, ?, ?, ?)";
if (!$insert = $mysqli->prepare($questionsql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}

$answersql = "INSERT INTO Answer (SessionId, QuestionId, Answer) 
VALUES (?, ?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}



//make sure both prepared statements succeeded before proceeding
if( $insert && $insertanswer)
{
$sessid =  $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$c = count($_POST['numQuestion']);

for($i = 0;  $i < $c; $i++ )
{

$selected_option = "A-C"; 
$selected_reply = "Single"; 


// Bind parameter for statement
$optionstmt->bind_param("s", $selected_option);

// Execute the statement
$optionstmt->execute();

if ($optionstmt->errno) 
{
// Handle query error here
echo __LINE__.': '.$optionstmt->error;
break 1;
}

// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$optionstmt->bind_result($optionid);

// This populates $optionid
$optionstmt->fetch();




// Bind parameter for statement
$replystmt->bind_param("s", $selected_reply);

// Execute the statement
$replystmt->execute(); //Line 236

if ($replystmt->errno) 
{
// Handle query error here
echo __LINE__.': '.$replystmt->error; //Line 241
break 2;
}

// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$replystmt->bind_result($replyid);

// This populates $optionid
$replystmt->fetch(); 

$insert->bind_param("sisiiii", $sessid, $_POST['numQuestion'][$i], $_POST['questionText'][$i],
$_POST['numberAnswer'][$i], $replyid, $_POST['textWeight'][$i],
$optionid);

$insert->execute();

if ($insert->errno) 
{
// Handle query error here
echo __LINE__.': '.$insert->error;
break 3;
}
}

$results = $_POST['value'];
foreach($results as $id => $value) 
{
$answer = $value;

$lastID = $id;



foreach($value as $answer) 
{
$insertanswer->bind_param("sis", $sessid, $lastID, $answer);

$insertanswer->execute();

if ($insertanswer->errno) {
// Handle query error here
echo __LINE__.': '.$insertanswer->error;
break 4;
}
}
}


//close your statements at the end


$insertanswer->close();
$insert->close();
$replystmt->close(); 
$optionstmt->close();
}
user1701484
  • 233
  • 1
  • 2
  • 12

1 Answers1

0

There's two different problems happening here. Firstly, the Commands out of sync warning is happening because you are trying to initiate new queries before actually finishing the previous ones. See this answer for more information about that. Basically, you have to close each of the queries you are preparing before preparing the next one.

As for the Cannot break/continue error, that is happening because you are calling break 2 when you are only 1 level deep. The optional number after break (or continue) is the number of 'levels' to break out of.

<?php
for($i = 0; $i < 10; $i++){
    // 1 level
    for($j = 0; $j < 10; $j++){
        // 2 levels

        break;      // Break of the $j loop
        break 1;    // Equivalent to above

        break 2;    // Break out of both the $j and $i loops

        break 3;    // Causes an error - there is no third level
    }
}

Of course, in that example it would never reach the other breaks after hitting the first one, but it should illustrate the concept. See also the documentation for break.

Community
  • 1
  • 1
Adam
  • 2,851
  • 1
  • 20
  • 20