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();
}
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.
Related
I have a web service where a user passes up a dynamic number of questions.
On the php side I am using explode with the ? to strip out each question. I then need to do a batch insert.
What I've done so far is as follows:
$checkInQs = explode("?", trim($_POST['checkInQs'], "?"));
$checkInSql = "INSERT INTO CheckListQs (ID, GeofenceID, type, question) VALUES ";
$checkInInsertQuery = array();
$checkInInsertData = array();
foreach($checkInQs as $q){
$checkInInsertQuery[] = "('',?, 1, ?)";
$checkInData[] = $geofenceID;
$checkInData[] = $q;
}
Based on another similar example, the following would be how to finish it off with pdo:
if (!empty($checkInInsertQuery)) {
$checkInSql .= implode(', ', $checkInInsertQuery);
$stmt = $db->prepare($checkInSql);
$stmt->execute($checkInData);
}
I'm not really sure how to bind the parameters in my case. I'm using procedural binding. I would usually bind parameters like so:
mysqli_stmt_bind_param($stmt, "is", $geofenceID, $question);
mysqli_stmt_execute($stmt);
I think the type part is as simple as:
$bindVar = '';
for ($i = 0; $i < count($checkInQs); $i++){
$bindVar .= "is";
}
But not I'm not sure how to manage passing in the rest of the data?
In the end, I chose to make use of transactions, commits and rollbacks to get my desired outcome:
mysqli_query($con, "start transaction;");
$allQueriesOK = true;
$checkInQs = explode("?", trim($_POST['checkInQs'], "?"));
$checkInSql = "INSERT INTO CheckListQuestions (ID, GeofenceID, type, question) VALUES ('',?,0,?)";
mysqli_stmt_prepare($stmt, $checkInSql);
foreach ($checkInQs as $q) {
mysqli_stmt_bind_param($stmt, "is", $geofenceID, $q);
if (!mysqli_stmt_execute($stmt)){
$allQueriesOK = false;
$message = mysqli_error($con);
break;
}
}
mysqli_stmt_close($stmt);
if ($allQueriesOK){
mysqli_query($con, "commit;");
}
else{
mysqli_rollback($con);
}
I successfully created a table in my database, using PHP. Now, I'm trying to fill it with data. When I var_dump the data I'm trying to add, it correctly renders - it's not undefined.
I don't get any errors, but there are no entries in my SQL tables. What did I do wrong? Thanks.
Database layout here:
foreach($x->channel->item as $entry) {
if ($y < 8) {
$con=mysqli_connect("localhost","usernameremoved",
"passwordremoved","databasenameremoved");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Entries (Link, Title)
VALUES ($entry->link, $entry->title)");
echo "Tables updated successfully.";
mysqli_close($con);
$y++;
}
}
UPDATE, for Watcher:
Parse error: syntax error, unexpected '$entry' (T_VARIABLE) in C:\xampp\htdocs\ (... ) \PHP\rss\index.php on line 60
if ($y < 8) {
mysqli_query($con,"INSERT INTO Entries (Link, Title)
VALUES ("$entry->link", "$entry->title")");
echo "Tables updated successfully.";
$y++;
}
This case is pretty much what prepared statements were created for.
// Database connection
$db = new MySQLi("localhost","usernameremoved", "passwordremoved","databasenameremoved");
if ($db->error) {
echo "Failed to connect to MySQL: ".$db->error;
}
// Prepared statement
$stmt = $db->prepare('INSERT INTO entries (Link, Title) VALUES (?, ?)');
if ($stmt === false) {
die('Could not prepare SQL: '.$db->error);
}
// Bind variables $link and $title to prepared statement
if ( ! $stmt->bind_param('ss', $link, $title)) {
die('Could not bind params: '.$stmt->error);
}
$y = 0;
foreach ($x->channel->item as $entry) {
if ($y >= 8) {
break;
}
// Set values on bound variables
$link = $entry->link;
$title = $entry->title;
// Execute
if ($stmt->execute() === false) {
die('Could not execute query: '.$stmt->error);
}
$y++;
}
$stmt->close();
$db->close();
Just take off that connect and close outside that loop. And as per Dagon, combine them into a multiple insert instead. Example:
$con = mysqli_connect("localhost","usernameremoved", "passwordremoved","databasenameremoved");
$stmt = 'INSERT INTO Entries (Link, Title) VALUES ';
$values = array();
$y = 0;
foreach ($x->channel->item as $entry) {
if($y < 8) {
$values[] = "('$entry->link', '$entry->title')";
}
$y++;
}
$values = implode(', ', $values);
$stmt .= $values;
mysqli_query($con, $stmt);
mysqli_close($con);
The Following code will display "12" on the screen. That is all. These echo numbers were added for debugging.
It should Display "123" and insert into a MySQL database the variables in the statement.
For some reason it just ends at the prepare statement. The fail() error check never getting called. Actually, nothing gets called after the prepare statement.
I have been all over the site and believe I am doing everything required properly, but it is more then likely something I did.
Can anyone tell me why the prepare statement is failing this way?
$query = "insert into member(mail, user, val) values (?, ?, ?)";
$uuu = blah#blah.com;
$hhh = Blah Williams;
$val = 0;
echo "1";
if($stmt = $this->conn)
{
echo "2";
$stmt->prepare($query) || $this->fail('MySQL prepare', $stmt->error);
echo "3";
$stmt->bind_param('ssi', $uuu, $hhh, $val)
|| $this->fail('MySQL bind_param', $stmt->error);
$stmt->execute();
if (!$stmt->execute())
{
if ($stmt->errno === 1062 /* ER_DUP_ENTRY */)
{
$this->fail('This username is already taken');
}
else
{
$this->fail('MySQL execute', $stmt->error);
}
}
}
else
{/*error check*/
$this->fail('MySQL insert prepare failed', $stmt->error);
return 0;
}
$stmt->close();
return true;
You should use as your assignment will always be true.
$stmt = $this->conn->prepare($query);
To check why it's failing, use:
var_dump($stmt->errorInfo());
I am receiving two errors in mysqli:
Warning: mysqli_stmt::execute(): (HY000/2014): Commands out of sync;
you can't run this command now in /.../ on line 235 240:
Commands out of sync; you can't run this command now Fatal error:
Cannot break/continue 2 levels in /.../ on line 241
I want to know that is the errors appearing because of the order of my queries and inserts below:
<?php
//connect to db
var_dump($_POST);
$optionquery = "SELECT OptionId FROM Option_Table WHERE (OptionType = ?)";
if (!$optionstmt = $mysqli->prepare($optionquery)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
$replyquery = "SELECT ReplyId FROM Reply WHERE (ReplyType = ?)";
if (!$replystmt = $mysqli->prepare($replyquery)) {
// 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();
if ($replystmt->errno)
{
// Handle query error here
echo __LINE__.': '.$replystmt->error;
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();
$results = $_POST['value'];
foreach($results as $id => $value)
{
$answer = $value;
$insert->bind_param("sisiiii", $sessid, $id, $_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;
}
$lastID = $insert->insert_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();
}
?>
This is because you are closing the statement at proper time
Close the statement $insertanswer->close(); at the proper place or before another query
I have a basic question asking how to use the isset(); command and how it should be written in the example below. I am trying to insert values into query, then retrive the last ImageId inserted and insert that into another table
session_start();
$imagesql = "INSERT INTO Image (ImageFile)
VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$img);
//Assign the variable
$img = 'ImageFiles/'.$_FILES['fileImage']['name'];
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
$lastImageID = $mysqli->insert_id;
$_SESSION['lastImageID'] = $lastImageID;
$imagequestionsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionId)
VALUES (?, ?, ?)";
if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err imagequestion";
}
$qnum = (int)$_POST['numimage'];
$insertimagequestion->bind_param("iii",$lastImageID, $sessionid, $qnum);
$insertimagequestion->execute();
if ($insertimagequestion->errno) {
// Handle query error here
}
$insertimagequestion->close();
Not exactly sure what your asking for, but guessing wildly:
session_start();
...... //PDO code and commands
$lastImageID = $mysqli->insert_id;
$_SESSION['lastImageID'] = $lastImageID;
if (isset($_SESSION['lastImageID'])) {
// do this
} else {
// do that
}
You only need to call isset if you are reading a variable that may not be defined.
In this situation, you are writing to $_SESSION['lastImageID'], so you don't need to check.
An example of where isset would be needed:
if (isset($_SESSION['lastImageID']))
{
$lastImageID = $_SESSION['lastImageID'];
}
else
{
$lastImageID = get_this_from_db_or_something();
}