mysqli::prepare is not returning an object? - php

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.

Related

How to fix "Incorrect date value: '2020' for column 'StartDate' at row 1" when trying to insert date into database

So I'm trying to insert data from a form which are, an id, 2 dates, a string, and a decimal. but it gives the error above.
columns are: ID:int, startdate:Date, enddate:Date, number:int, string, Decimal.
I have already tried adding all those date() functions and strtodate() and stuff like that, but nothing worked.
if (isset($_POST['submitReservation'])) {
$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];
$linens = mysqli_real_escape_string($conn, $_POST['linens']);
$peopleAmount = mysqli_real_escape_string($conn, $_POST['persons']);
$number = 50;
$userID = $_SESSION["UserID"];
$sql = $conn->prepare("INSERT INTO reservation (TenantId, StartDate, EndDate, Number_Of_Persons, Linens, Cost) VALUES (?, ?, ?, ?, ?, ?)");
$sql->bind_param("iiiisd", $userID, $startDate, $endDate, $peopleAmount, $linens, $number);
$sql->execute() or die(mysqli_error($conn));
}
You are casting the dates to int $sql->bind_param("iiiisd"
Edit: MySQL expects a string, so try $sql->bind_param("issisd"
If you are using the standard PDO library you can use bindParam() or bindValue() and specify the type e.g.
if (isset($_POST['submitReservation'])) {
$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];
$linens = $_POST['linens']);
$peopleAmount = $_POST['persons']);
$number = 50;
$userID = $_SESSION["UserID"];
$sql = $conn->prepare("INSERT INTO reservation (TenantId, StartDate, EndDate, Number_Of_Persons, Linens, Cost) VALUES (?, ?, ?, ?, ?, ?)");
$sql->bindParam(1, $userID, PDO::PARAM_STR);
$sql->bindParam(2, $startDate, PDO::PARAM_STR);
$sql->bindParam(3, $endDate, PDO::PARAM_STR);
$sql->bindParam(4, $peopleAmount, PDO::PARAM_INT);
$sql->bindParam(5, $linens, PDO::PARAM_STR);
$sql->bindParam(6, $number, PDO::PARAM_INT);
$sql->execute();
}

Inserting multiple string into mysql using bind_param

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

Not working mysql query with prepared statements

I'm trying to understand where I am wrong with this query..
$query = "INSERT INTO turni (data, utenteId, turno_ceduto, tipo_turno_ceduto,
turno_cercato,
note, date) VALUES (?, ?, ?, ?, ?, ?, NOW())";
$stmt = mysqli_prepare($dbc,$query);
mysqli_stmt_bind_param($stmt,'sissss', $data, $utenteId, $turno_ceduto,
$tipo_turno_ceduto, $turno_cercato, $note);
mysqli_stmt_execute($stmt);
$count = mysqli_stmt_affected_rows($stmt);
Why is $count -1??
Question
Why is $count -1??
Answer
-1 indicates that the query has returned an error
mysqli_stmt_affected_rows
You shoud check errors with mysqli_error, it's returns a string description of the last error.
You get the error description from the last mysqli-function, not from the last mysql-error.
You should always check for errors after each prepare() and execute(), and report the errors.
Here's an example:
if (($stmt = mysqli_prepare($dbc,$query)) === false) {
trigger_error(mysqli_error($dbc), E_USER_ERROR);
}
mysqli_stmt_bind_param($stmt,'sissss', $data, $utenteId, $turno_ceduto,
$tipo_turno_ceduto, $turno_cercato, $note);
if (mysqli_stmt_execute($stmt) === false) {
trigger_error(mysqli_stmt_error($stmt), E_USER_ERROR);
}
$count = mysqli_stmt_affected_rows($stmt);

Query isn't getting executed

Can some onw please explain what is wrong with this ... this worked completely fine with procedural php
function foo(){
$incomingtime = date('Y-m-d H:i:s', time());
$stmt = $db->stmt_init();
$id = "Abc123" ;
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$stmt->execute();
printf("Affected rows (UPDATE): %d\n", $db->affected_rows); // Always return 1
$stmt->close();
}
But nothing goes in the database.
Datatype in mysql db for indate is datetime
There's several issues with this code.
$stmt_4 is used before it's defined.
$u_id and $c_id are both defined then not used.
Trying to execute $stmt without supplying parameters.
$db is not defined.
$id is not defined.
If you are trying to convert working code to a function make sure that either the function gets these passed in as an argument, they are marked as global or the function creates/ retrieves them.
Check changing:
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$u_id = 1;
$c_id = 1;
$stmt->execute();
to:
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (CURRENT_TIMESTAMP, ?, ?, ?)"
$stmt = $db->prepare($query);
$stmt->execute(array($id, $u_id, $c_id));
NOTE: I deleted the parameter ssii because it's not considered in the query. It only expects 4 parameters.

SQL INSERT bind not working

When I call the function updatePost($postID, $postTitle, $postContent, $catID) it calls it but fails on the first line $stmt = db::connect()->prepare. I am accessing my database the same way for all other functions but this one is failing. Why?
function updatePost($inPostID, $inPostTitle, $inPostContent, $inCatID)
{
var_dump($stmt);
$stmt = db::connect()->prepare("UPDATE Posts SET postTitle = ?, postContent = ?, postCatID = ?, WHERE postID = ?");
var_dump($stmt);
$stmt->bind_param('ssii', $inPostTitle, $inPostContent, $inPostCatID, $inPostID);
$stmt->execute();
$stmt->close();
}
Lose the last comma in your SQL statement:
UPDATE Posts SET postTitle = ?, postContent = ?, postCatID = ? WHERE postID = ?

Categories