MySQLi prepared insert statement fails - php

I am updating my PHP to use mysqli:: instead of mysql_* and I have run into an issue with INSERT statements. I have the following statement:
$stmt = $link->prepare("INSERT INTO `table` (`a`, `b`, `c`) VALUES(?, ?, ?)");
$stmt->bind_param("sss", $a, $b, "0");
$stmt->execute();
I have checked $stmt and it is a proper mysqli_stmt object. It is prepared properly, but for some reason, the statement won't execute. I just get a 500 error from my server.
What am I missing?
Edit
I've determined that the issue is coming from the bind_param method.
Edit 2
Okay, so the error PHP is giving me is this:
Fatal error: Cannot pass parameter 4 by reference in...
This points to the line of bind_param

You can't pass a constant to bind_param. Put the value in a variable first:
$status = "0";
$stmt->bind_param("sss", $oid, $cid, $status);
$stmt->execute();

Related

Warning: mysqli_stmt:: execute() expects exactly 0 parameters, 1 given in [duplicate]

I have this code in MyFile.php
$db= mysqli_connect("host","user","pw","db");//connect to db
if (mysqli_connect_errno($con))//check connection
{echo "Failed to connect to MySQL: " . mysqli_connect_error();}
//Create a token for the unique link
$title= $_GET[apt_title];
$email= $_GET[mail_address];
$token = sha1(uniqid($email, true));
$time = $_SERVER["REQUEST_TIME"];
//prepare the query to be executed
$query = $db->prepare(
"INSERT INTO pending_users (email, token, title_apt, tstamp) VALUES (?, ?, ?, ?)"
);
$query->execute(
array(
$title,
$email,
$token,
$time
)
);
Error message:
Warning: mysqli_stmt::execute() expects exactly 0 parameters, 1 given in /websites
How should I call execute() the right way?
Because mysqli::execute() does not accept any parameters. Before calling it, you have to prepare the query and then bind the params to the query. Then you have to call the execute() method. So try like this:
$query = $db->prepare(
"INSERT INTO pending_users (email, token, title_apt) VALUES (?, ?, ?, ?)"
);
$query->bind_param('ssss', $title, $email, $token, $time);
$query->execute();
For more check the documentation
Passing parameters in execute() is available only as of PHP 8.1. You need to upgrade your PHP version or use the old bind_param().
you need to bind params before executing the query,
in procedural way do like this
mysqli_stmt_execute($stmt);
if you are doing it like object oriented way after binding params
/* Execute the statement */
$stmt->execute();
Docs link.
http://www.php.net/manual/en/mysqli-stmt.execute.php
If you look at the manual for mysqli::execute(), you'll see that it does not accept any parameters.
bool mysqli_stmt::execute ( void )
Instead, you should use mysqli::bind_param to bind your parameters.

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.

MySQL - Number of variables doesn't match number of parameters in prepared statement

So i have the query below which runs perfectly, but I get the error in the title and I don't understand why. Maybe someone can help.
Query:
$stmt = $mysqli->prepare("INSERT INTO paypal_log (product_name) VALUES ('".$_POST["product_name"]."')");
$stmt->bind_param('s', $product_name);
$stmt->execute();
$stmt->close();
Error:
PHP Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in /home/triponsergiu/public_html/test/includes/paypal.php on line 29
Thank you.
Binding parameters to statements means filling in a parameter in the statement that was left 'blank'. To create a 'blank', replace a value with, for example, a question mark.
$stmt = $mysqli->prepare('INSERT INTO paypal_log (product_name) VALUES (?)');
$stmt->bind_param('s', $product_name);
$stmt->execute();
$stmt->close();
This way, the parameter is automatically escaped (so they can't delete or download your entire database...).
$stmt = $mysqli->prepare("INSERT INTO paypal_log (product_name) VALUES (?)");
$stmt->bind_param('s', $_POST["product_name"]);
Consult the manual on prepared statements.

When is it necessary to bind parameters with MySQLi?

From this code I received an error.
//Prepare insert statement.
if($InsertEventQuery = $mysqli->prepare("INSERT into events(eventname, eventdesc, eventmonth, eventdate, eventyear, eventstart, eventend) VALUES ('$EventName','$EventDesc','$EventMonth','$EventDate','$EventYear','$EventStart','$EventEnd')"))
{
//Bind parameters of insert statement.
$InsertEventQuery->bind_param('ssiiiii', $EventName, $EventDesc, $EventMonth, $EventDate, $EventYear, $EventStart, $EventEnd);
This is the error:
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in[...]
I looked into it because the error appears to be incorrect and found:
PHP Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement
You do not need to bind parameters in this case. Placeholders are used for the values in an INSERT statement, or in a WHERE clause. (Note that placeholders are not allowed for identifiers, such as the column names in your statement.)
This confused me and I am now wondering in interest of security, when is it necessary to bind parameters and when is it necessary to use placeholders.
Binding parameters is a good idea in any INSERT statement as it will prevent SQL injection, and will also sanitize your strings for free.
I usually get it working using question mark in prepare statement like this:
//Prepare insert statement.
if ($InsertEventQuery = $mysqli->prepare("INSERT into events(eventname, eventdesc, eventmonth, eventdate, eventyear, eventstart, eventend) VALUES (?, ?, ?, ?, ?, ?, ?)"))
{
//Bind parameters of insert statement.
$InsertEventQuery->bind_param('ssiiiii', $EventName, $EventDesc, $EventMonth, $EventDate, $EventYear, $EventStart, $EventEnd);

prepared INSERT statement to get insert_id to use in a second prepared INSERT statement

Im trying to create my own register form but im having issues with prepared statements.
the idea is to create a prepared statement to insert info into the user table, then from that get the insert_id from the generated content to use in another insert statement
here is a version of my register script
<?php
$returnedId = '';
include "includes/dbconnect.php";
$stmt = $db->prepare("INSERT INTO `users`(`Username`, `Email`, `Password`) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $_POST['username'], $_POST['email'], $_POST['password']);
$stmt->execute();
$returnedId = $stmt->insert_id;
$stmt->close();
echo $returnedId;
$allergystmt = $db->prepare("INSERT INTO 'user_allergy' ('user_id', 'allergy_id') VALUES (?, ?)");
$allergystmt->bind_param('ss', $returnedId, $_POST['check_list']);
$allergystmt->execute();
$allergystmt->close();
header('Location: index.php');
?>
the first prepared statement runs correctly and inserts information into the table, after that the $returnId variable is successfully echoed. next in the script is my second prepared statement, when it tries to run im getting the error that says:
Fatal error: Call to a member function bind_param() on a non-object in D:\filepath\register.php on line 17
it seems that my variable isnt being carried into the second prepared statement.
Your second query has syntax errors and failed to prepare. Since you have no error handling for database failures like this, your later code just blunders onwards:
$allergystmt = $db->prepare("INSERT INTO 'user_allergy' ('user_id', 'allergy_id') VALUES (?, ?)");
^--- ^--^--- ^-- etc...
You cannot use ' quotes on table and field names. ' indicate strings. None of those field/table names are reserved words, so there is NO need to quote them at at all:
$allergystmt = $db->prepare("INSERT INTO user_allergy (user_id, allergy_id) VALUES (?, ?)");
if (!$allergystmt) { die($dbh->errorInfo()); }
Note the addition of the errorInfo() output. Never assume a DB operation was successful. Always assume failure, and treat success as a pleasant surprise.

Categories