Not working mysql query with prepared statements - php

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

Related

Mysqli bind parameters not working

I'm trying to use prepared statements to enter data in a database. The unprepared statement works but this prepared statement does not. I can't find out why.
Prepared version:
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $newstring, $id, $date->format('Y-m-d'), $location);
$stmt->execute();
Unprepared version:
$sql = "INSERT INTO videos (file_name, upload_by, date, path) VALUES ('$newstring', '$id', '
$date', 'Nominator/$location$newstring')";
mysqli_query($mysqli, $sql);
Replace $stmt-execute(); with $stmt->execute();
Also, don't use date and path in query. Rename them with some other name like date1 and path1.
Update your Query like below that will surely work (Tested Offline):
<?php
$mysqli = new mysqli('localhost', 'root', '', 'test2');
if ($mysqli->errno) {
printf("Connect failed: %s\n", $mysqli->error);
exit();
}
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date1, path1) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $file_name, $upload_by, $date1, $path1);
$date1 = date("Y-m-d");
$file_name = "test.jpg";
$upload_by = "amit";
$path1 = "test";
if ($result = $stmt->execute()){
echo "success";
$stmt->free_result();
} else {
echo "error";
}
$stmt->close();
?>
You are binding your parameter twice, if you are using only ?, don't bind parameter again just execute directly.
//Prepare your query first
$stmt = $mysqli->prepare("INSERT INTO videos (file_name, upload_by, date, path)
VALUES (?, ?, ?, ?)");
//Just pass your argument and execute directly without binding the parameter (The parameter is binded already)
$stmt->execute('ssss', $newstring, $id, $date->format('Y-m-d'), $location);

PHP Prepared Statement Failing When Calling MySQL Function

I've been using prepared statements for a good while now with no issues but today when I tried to call a MySQL function from a prepared statement I'm getting the following:
Fatal error: Call to a member function fetch_array() on boolean in DB.php on line 336
This is the code I'm using and there is nothing different from my usual SELECT, UPDATE or DELETE querys, I also have no issues calling procedures, granted none of my procedures are returning any value.
$sql = "SELECT FN_MAINTAIN_ASSET(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) AS assetId;";
try {
$conn = $this->open();
$stmt = $conn->prepare($sql);
if($stmt === false) {
trigger_error(sprintf($txt["error_sql"], $conn->error), E_USER_ERROR);
}
$stmt->bind_param('iiiisssbbiiiis', $modify, $type, $category, $year, $title, $description, $imageFilename, $imageMain, $imageThumbnail, $membersOnlyView, $privateView, $status, $memberId, $createdIp);
$stmt->execute();
$rs = $stmt->get_result();
$result = $rs->fetch_array(MYSQL_ASSOC); // Line 336
$rs->free();
$stmt->close();
$this->close($conn);
} catch (Exception $e) {
$logObj->error($e->getMessage());
}
$rs is empty just before line 336, no error messages from $stmteither.
If anyone has any suggestions or ideas, greatly appreciated.
From the manual for get_result:
Return Values
Returns a resultset for successful SELECT queries, or FALSE for other
DML queries or on failure. The mysqli_errno() function can be used to
distinguish between the two types of failure.
If your statement is returning a boolean, it failed. Check the error message from $stmt->error, and correct whatever's wrong.

Catch Duplicate entry with prepared SQL statement

I want to handle the "Duplicate entry" error with a prepared MySQL statement.
I have thoses lines
$result = $db->prepare("INSERT INTO comptability (id_comptability, order_id, Reduction, `%TVA`, Facture) VALUES (?, ?, ?, ?, ?)");
$result->execute(array($no_facture, $id_order, $reduc_tot, $tot, $date));
And want to execute some code if there is not any error. And display a pop-up and make the prog die if there is an error.
I already tried
if($result === false)//Catch error
{}
else //It worked
{}
But it did not worked
You can use INSERT IGNORE and then check how many rows were affected using PDOStatement::rowCount
Concept should be along the lines of:
$result = $db->prepare("INSERT IGNORE INTO comptability (id_comptability, order_id, Reduction, `%TVA`, Facture) VALUES (?, ?, ?, ?, ?)");
if ($result->execute(array($no_facture, $id_order, $reduc_tot, $tot, $date))) {
if ($result->rowCount() == 0) {
// You had a duplicate record.
} else {
// all good.
}
}

Insert query not inserting no error message

I can't get an INSERT query to INSERT in db. I am not getting any error message and was following a tutorial any help will be greatly appreciated.
$query = "INSERT INTO rooms (room_title,room_description,monthly_rate,prop_name,prop_description) VALUES ( ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($dbc,$query);
//$stmt = mysqli_query($dbc, $query);
if($stmt == false) {
die("<pre>".mysqli_error($dbc).PHP_EOL.$query."</pre>");
}
mysqli_stmt_bind_param($stmt,"ssiss",$pn,$d,$p,$ppn,$ppd);
mysqli_stmt_execute($stmt);
//mysqli_stmt_close($stmt);
// Check the results...
if (mysqli_stmt_affected_rows($stmt) == 1)
{
echo'<p>The room has been added.</p>';
// Clear $_POST:
$_POST = array();
}
mysqli_stmt_close($stmt);
} // End of $errors IF.
// End of the submission IF.
Because it does not echo "The room has been added" I suspect the problem is with the mysqli_stmt_affected_rows($stmt) == 1
try this
if ($stmt = mysqli_prepare($dbc, "INSERT INTO rooms (room_title,room_description,monthly_rate,prop_name,prop_description) VALUES ( ?, ?, ?, ?, ?)")) {
mysqli_stmt_bind_param("ssiss",$pn,$d,$p,$ppn,$ppd);
mysqli_stmt_execute($stmt);
} printf("Error: %s.\n", mysqli_stmt_error($stmt));

mysqli::prepare is not returning an object?

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.

Categories