I've created below function which include several mysql queries, which seem to create an issue. Cause when I run this function it returns following error:
Errormessage: Commands out of sync; you can't run this command now
I've tried to include next_result(), but does not do any difference?
function retrievePlayerTweets(){
global $con;
$query = $con->prepare("Select players.fullname, players.twitter_user, team.id as teamId FROM players, team WHERE players.teamId = team.id");
$query->execute();
$query->bind_result($fullname, $twitter_user, $teamId);
while ($query->fetch()) {
foreach(retrieveUserTweets($twitter_user) as $twitterData) {
$id = $twitterData['id_str'];
$text = $twitterData['text'];
$name = $twitterData['user']['name'];
$dateString = $twitterData['created_at'];
$favoriteCount = $twitterData['favorite_count'];
$date = date('Y-m-d H:i:s', strtotime($dateString));
if ($insert_tweet = $con->prepare("INSERT IGNORE INTO tweets (`fullname`, `username`, `text`, `created`, `teamId`, `twitterId`, `favoriteCount`) VALUES (?, ?, ?, ?, ?, ?, ?)")) {
$insert_tweet->bind_param("ssssisi", $name, $twitter_user, $text, $date, $teamId, $id, $favoriteCount);
$insert_tweet->execute();
$con->next_result();
} else {
die("Errormessage: ". $con->error);
}
}
}
}
If you get Commands out of sync; you can't run this command now in your client code, you are calling client functions in the wrong order.
This can happen, for example, if you are using mysql_use_result() and try to execute a new query before you have called mysql_free_result(). It can also happen if you try to execute two queries that return data without calling mysql_use_result() or mysql_store_result() in between.
https://dev.mysql.com/doc/refman/5.0/en/commands-out-of-sync.html
Related
I am attempting to update a row in my database where the users IP address and email address from an email are the used in the where clause of the query.
public function insert_user_captured_data($userip, $didIclickemaillink, $emailclickedfrom, $fname, $lname, $emailentered, $submitclicked){
$sql = "UPDATE testdata
SET useripclicked = ?,
emailclickedfromhere = ?,
userlinkclicked = ?,
userfnameentered = ?,
userlnameentered = ?,
useremailentered = ?,
usersubmittedform = ?,
timestamp = CURRENT_TIMESTAMP
WHERE useripclicked = ? AND emailclickedfromwhere = ?";
$stmnt = $this->dbConnection->prepare($sql);
$stmnt->bind_param("ssisssiss",$userip,$emailclickedfrom,$didIclickemaillink,$fname,$lname,$emailentered,$submitclicked,$userip,$emailclickedfrom);
$insRes = $stmnt->execute();
if (!$insRes) {
throw new Exception("Error Processing Request: Row Not inserted $stmnt->error", 1);
}
}
I am successful in the initial insert but want to update the second pass to fill in the rows after the user has filled out a contact form. I get the following error (in code tags to stand out)
Fatal error: Uncaught Error: Call to a member function bind_param() on boolean in C:\wamp64\www\example.com\assets\php\database.php:73 Stack trace: #0 C:\wamp64\www\example.com\assets\php\thankyou.php(37): Database->insert_user_captured_data('10.0.2.15', 'jfender#example.com', 'Jesse', 'Fender', 'jfender#example.com', 1) #1 {main} thrown in C:\wamp64\www\example.com\assets\php\database.php on line 73
Additionally removed some of the repeated values that really didn't need to be updated with the following as a result:
public function insert_user_captured_data($userip, $emailclickedfrom, $fname, $lname, $emailentered, $submitclicked){
$sql = "UPDATE testdata
SET userfnameentered = ?,
userlnameentered = ?,
useremailentered = ?,
usersubmittedform = ?,
timestamp = CURRENT_TIMESTAMP
WHERE useripclicked = ? AND emailclickedfromwhere = ?";
$stmnt = $this->dbConnection->prepare($sql);
$stmnt->bind_param("sssiss",$fname,$lname,$emailentered,$submitclicked,$userip,$emailclickedfrom);
$insRes = $stmnt->execute();
if (!$insRes) {
throw new Exception("Error Processing Request: Row Not inserted $stmnt->error", 1);
}
}
But am getting the same error, and printing out the error and stack trace have been no help at all...
What am I doing wrong? I'm currently using PHP 7.1.9, MySQL 5.7.19, and Apache 2.4.17 On a Windows 10 system I am using OOP mysqli, and have been inserting just fine in my table.
Im so Sorry guys... I found the error... it happened in the prepare() and it was due to my entering an erroneous letter in one of the column names. here is the corrected code::
public function insert_user_captured_data($userip, $emailclickedfrom, $fname, $lname, $emailentered, $submitclicked){
$sql = "UPDATE testdata
SET userfnameentered = ?,
userlnameentered = ?,
useremailentered = ?,
usersubmittedform = ?,
timestamp = CURRENT_TIMESTAMP
WHERE useripclicked = ? AND emailclickedfromhere = ?";
$stmnt = $this->dbConnection->prepare($sql);
$stmnt->bind_param("sssiss",$fname,$lname,$emailentered,$submitclicked,$userip,$emailclickedfrom);
$insRes = $stmnt->execute();
if (!$insRes) {
throw new Exception("Error Processing Request: Row Not inserted $stmnt->error", 1);
}
}
Jesse Fender
Nice, prepare returns false when there is an SQL error. To track them easier you can make a quick check. Hope it helps:
if ($stmt = $this->dbConnection->prepare("QUERY")) {
$stmt->bind_param(...);
} else {
echo "Prepare error: {$this->dbConnection->errno} - {$this->dbConnection->error}";
}
How can I troubleshoot further? I have 3 styles of querying. This is for a fetchType = 'single' ( single row that is) and a populated parameterArray
public function query($fetchType, $queryType, $parameterArray=null)
{
$query=$this->sql_array[$queryType];
if($parameterArray==null)
{
$pdoStatement = $this->db_one->query($query);
$results = $pdoStatement->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$this->db_one->quote($query);
$pdoStatement = $this->db_one->prepare($query);
$results = $pdoStatement->execute($parameterArray);
if($fetchType=='single')
{
$results = $pdoStatement->fetch(PDO::FETCH_ASSOC);
}
else if($fetchType=='multiple')
{
$results = $pdoStatement->fetchAll(PDO::FETCH_ASSOC);
}
return $results;
}
My results is coming back false and I see no data in the sql table.
I verified that the queryType exists in the lookup table and that other queries are working.
Here is the actual query. I inserted new lines to make readable.
"signup_insert" =>
"INSERT INTO credentials
(h_token, h_file, h_pass, email, name, picture, privacy)
VALUES (?, ?, ?, ?, ?, ?, ?)"
Here is the debug code I created:
$pipe['debug_h_token']=$h_token;
$pipe['debug_h_file']=$h_file;
$pipe['debug_h_pass']=$h_pass;
$pipe['debug_email']=$this->TO->get('email');
$pipe['debug_name']=$this->TO->get('name');
$pipe['debug_picture']=$picture;
$pipe['debug_privacy']=$privacy;
$test = $this->DBO->query('single', 'signup_insert', array(
$h_token,
$h_file,
$h_pass,
$this->TO->get('email'),
$this->TO->get('name'),
$picture,
$privacy
));
$pipe['debug_test'] = $test;
This question already has answers here:
Call to a member function bind_param() on a non-object [duplicate]
(6 answers)
Closed 6 years ago.
So I'm having the same problem for 3 hours straight and I've been searching Stack Overflow, Google and even Bing (yes even Bing..) for the right answer but I can't seem to find a solution...
The problem:
I try to insert data into my database using a prepared statement, but I keep getting the same error over and over again. I'm using everything in the right order and stuff so that's not the mistake...
My code:
//INCLUDES FILES THAT HOLD ALL DATA (servername, username, ...)
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO REGISTRY (user_ref, email_user, date_created, title, tweet, description, category, filename, invoice) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssssss", $gebruikerID, $email, $date_created, $title, $tweet, $description, $category, $nameImage, $customUniqueId);
// set parameters and execute
$gebruikerID = $gebruikerID;
$email = $email;
$date_created = date("d/m/Y H:i:s");
$title = date("d/m/Y H:i:s");
$tweet = $_POST["tweet"];
$description = $_POST["project_description"];
$category = $_POST["category"];
$nameImage = $nameImage;
$customUniqueId = $_GET["redirect"];
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
The error I'm getting for 3 hours straight:
Fatal error: Call to a member function bind_param() on a non-object on line 148
For those of you that have the same problem like me, here's what was wrong:
I had forgotten to put every row of my database in the code... So what I ended up was go to phpmyadmin and go to the table i wanted to insert some data in. Then I clicked SQL and I chose insert.
After that, I got a code and I replaced all [val-x] with ? And ended up with this code:
// prepare and bind
$stmt = $conn->prepare("INSERT INTO `projecten`(`user_ref`, `email_user`, `date_created`, `title`, `tweet`, `description`, `category`, `filename`, `invoice`, `admin_checkup`, `visible`, `project_finished`, `deleted`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("sssssssssssss", $gebruikerID, $email, $date_created, $title, $tweet, $description, $category, $nameImage, $customUniqueId, $adminCheck, $visible, $project_finished, $deleted);
// set parameters and execute
$gebruikerID = $gebruikerID;
$email = $email;
$date_created = date("d/m/Y H:i:s");
$title = date("d/m/Y H:i:s");
$tweet = $_POST["tweet"];
$description = $_POST["project_description"];
$category = $_POST["category"];
$nameImage = $nameImage;
$customUniqueId = $_GET["redirect"];
$adminCheck = "0";
$visible = "0";
$project_finished = "0";
$deleted = "0";
$stmt->execute();
I hope this helps you guys out!
I'm retrieving tweets from the twitter api, which i'm trying to save in my database however i keep getting an error, which i cant seem to fix. i've checked the number of parameters is correct and everything should be okay, so i dont see why i get following error:
Fatal error: Call to a member function bind_param() on a non-object
tweets database:
function retrievePlayerTweets(){
global $con;
$query = $con->prepare("Select players.fullname, players.twitter_user, team.id as teamId FROM players, team WHERE players.teamId = team.id");
$query->execute();
$query->bind_result($fullname, $twitter_user, $teamId);
while ($query->fetch()) {
foreach(retrieveUserTweets($twitter_user) as $twitterData) {
$id = $twitterData['id_str'];
$text = $twitterData['text'];
$name = $twitterData['user']['name'];
$dateString = $twitterData['created_at'];
$favoriteCount = $twitterData['favorite_count'];
$date = date('Y-m-d H:i:s', strtotime($dateString));
$insert_tweet = $con->prepare("INSERT IGNORE INTO tweets (`fullname`, `username`, `text`, `created`, `teamId`, `twitterId`, `favoriteCount`) VALUES (?, ?, ?, ?, ?, ?, ?)");
$insert_tweet->bind_param("ssssisi", $name, $twitter_user, $text, $date, $teamId, $id, $favoriteCount);
$insert_tweet->execute() or die(mysqli_error($con));
}
}
}
The problem is with your $con variable which is not connecting to the database, due to which the methods inside cannot be called.
also it is good pratice to add die() function to print error message after call to the execute function in PDO or mysqli, to see error in query use:
if using PDO:
$insert_tweet->execute() or die(print_r($con->errorInfo()));
if using mysqli:
$insert_tweet->execute() or die(mysqli_error($con));
I got some problem with binding some parameters in MYSQL statement in php. It is throwing an error when count($posts) > 1 on the marked line below. Anyone who know what I've done wrong?
The error is: Call to a member function bind_param() on a non-object. It is also reporting comman out of sync?(on the marked line below)
<?php
include '../../main/mainFunctions2.php';
$futurePosts = json_decode($_POST['futurePosts']);
$repeatSerie = null;
if(count($posts) > 1){
//Get new repeatSeries
$stmt = $mysqli->prepare("
SELECT repeatSerie
FROM timeSpaces_futurePosts
ORDER BY repeatSerie DESC
LIMIT 1
");
$stmt->execute();
$stmt->bind_result($repeatSerie);
$stmt->fetch();
$repeatSerie = ((int)$repeatSerie + 1);
}
$timeStamp = time();
foreach($posts as $fp){
$title = $fp->title;
$startDate = $fp->startDate;
$endDate = $fp->endDate;
$startTime = $fp->startTime;
$endTime = $fp->endTime;
$location = $fp->location;
$latLong = $fp->latLong;
$info = $fp->info;
$photoId = $fp->photoId;
$invited = $fp->invited;
if($invited != null){
$invited = 1;
}else{
$invited = 0;
}
$reminderType = $fp->reminderType;
$reminderTimeStamp = $fp->reminderTimeStamp;
$repeatSerie = $repeatSerie;
$stmt = $mysqli->prepare("
INSERT INTO futurePosts (profileId, title, startDate, endDate, startTime, endTime, location, latLong, info, photoId, invited, reminderType, reminderTimeStamp, repeatSerie)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param('isssiisssiisii', $profileId, $title, $startDate, $endDate, $startTime, $endTime, $location, $latLong, $info, $photoId, $invited, $reminderType, $reminderTimeStamp, $repeatSerie);
//The line above: Call to a member function bind_param() on a non-object
$stmt->execute();
$futurePostId = $mysqli->insert_id;
if($invited == 1){
foreach($fp->invited as $friendsId){
$friendsId = $friendsId;
$stmt = $mysqli->prepare('
INSERT INTO futurePosts_invited (profileId, futurePostId, timeStamp)
VALUES (?, ?, ?)
');
$stmt->bind_param('iii', $friendsId, $futurePostId, $timeStamp);
$stmt->execute();
}
}
}
echo 'TRUE';
?>
This is most likely because $stmt = $mysqli->prepare(...); line fails due to SQL syntax error. Try echoing $mysqli->error to see what's wrong with it.
Try calling $stmt->store_result(); after execution of your SELECT statement and before issuing any other queries to MySQL.
Side note: you should prepare your statement before foreach loop. That will get you a bit of performance gain, since the statement will only be compiled once and only parameters will be sent to server on each loop run.
mysqli_prepare() returns a statement object or FALSE if an error
occurred.