When is it necessary to bind parameters with MySQLi? - php

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

Related

PHP Prepared Statement SQL with where value

I am trying to run this query on an existing row in sql table:
if($stmt = $mysqli->prepare("INSERT INTO 4rounds (player2_name, player2_army1_name, player2_army2_name, player2_army3_name, player2_army4_name, player2_identifier, player2_stage, player2_army1_position, player2_army2_position, player2_army3_position, player2_army4_position) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) WHERE pairing_id = ?")) {
but it returns the error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE pairing_id = ?' at line 1
The query works without the WHERE clause. I think there is a problem with binding the parameter in this matter and I should use VALUE as well to bind it later but I can't seem to find anything online about binding a param in this manner.
These are the binds I am trying with:
$stmt->bind_param("ssssssssssss", $player2_name, $player2_army1_name, $player2_army2_name, $player2_army3_name, $player2_army4_name, $player2_identifier, $player2_stage, $player2_army1_position, $player2_army2_position, $player2_army3_position, $player2_army4_position, $pairing_id);
INSERT statements don't have WHERE clauses, and I'm not sure why you would want such a thing... Those only exist in SELECT and UPDATE queries, typically.

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.

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.

Insert into table with prepared statement

I'm trying to insert data from a form into a database using PHP and Mysqli but I can't get it working! My database has 4 fields: DATE, TITLE, CONTENT, ID. The ID field is auto-increment.
I've checked the connection and that's working fine. I've also echoed the form field values and the $blogDate variable I created, they're all fine too.
Here's my prepared statement:
if ($newBlog = $mysqli->prepare('INSERT INTO Blog VALUES ($blogDate, $_POST["bTitle"], $_POST["bContent"])')) {
$newBlog->execute();
$newBlog->close();
}
It's just not inserting the values into my table.
You are generating SQL containing strings that are not quoted or escaped.
Don't insert the data directly into the SQL string, use placeholders (?) and then bind the parameters before executing.
$query = "INSERT INTO Blog VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();
Since you are aware about prepared statement:
$newBlog = $mysqli->prepare('INSERT INTO Blog (`dateCol`, `titleCol`, `contentCol`) VALUES (?, ?, ?)');
$newBlog->bind_param( 'sss', $blogDate, $_POST["bTitle"], $_POST["bContent"] );
$newBlog->execute();
$newBlog->close();
since you are using auto increment field you need to specify column name and then values
try this code
$query = "INSERT INTO Blog (colname_1,colname_2,colname_3) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $blogDate, $_POST["bTitle"], $_POST["bContent"]);
$stmt->execute();

Prepared statement mysqli

I'm getting obsessed. I'm working for the first time with prepared statement and I am sure I have read somewhere that you could prepare a statement like:
$stmt = $db->prepare("INSERT INTO {$table} (:var1, :var2) VALUES (:val1, :val2)");
$stmt->bind_param(':var1', $var1);
$stmt->bind_param(':var2', $var2);
$stmt->bind_param(':val1', $val1);
$stmt->bind_param(':val2', $val2);
$stmt->execute();
Or something like that. I remember that I have read that you could call the vars with a specific name with ':' as prefix. But I really can't find an example of that. I read the php manual and I couldn't find any sample of this thing.
Is it right or have I dreamed it?
Faq
If you are wondering why I can't use simply the '?' method:
$stmt = $db->prepare("INSERT INTO {$table} (?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?)");
this gets hard to write.
You can't do :var1,:var2,:varX in both the column names list and the VALUES list for one thing. Secondly, PDO accepts named parameter binding.
See PHP Data Objects and examples in PDO::prepare.

Categories