Prepared statement mysqli - php

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.

Related

PHP mysqli prepare statement bind_param boolean error

Testing the statement from all side, but failed to find a solution for it.
// Insert the new user into the database
if( $insert_stmt = $mysqli->prepare("INSERT INTO client (username, email,
password, reg_ip, salt, country, ref_id, pin, ref_by, ref_by_2) VALUES ( ?,
?, ?, ?, ?, ?, ?, ?, ?, ?)")){
$insert_stmt->bind_param("ssssssssii", $username, $email, $pass_2,
$reg_ip, $random_salt, $countryname, $ref_code, $hashed_pin, $user_id3,
$user_id4);
$insert_stmt->execute();
This never executes or gets inside the if statement.
I debugged it by removing the if part, that shows bind_param() is boolean error.
$insert_stmt = $mysqli->prepare("INSERT INTO client (username, email,
password, reg_ip, salt, country, ref_id, pin, ref_by, ref_by_2) VALUES ( ?,
?, ?, ?, ?, ?, ?, ?, ?, ?)");
$insert_stmt->bind_param("ssssssssii", $username, $email, $pass_2, $reg_ip,
$random_salt, $countryname, $ref_code, $hashed_pin, $user_id3, $user_id4);
if($insert_stmt->execute()){
Fatal error: Call to a member function bind_param() on boolean
I have done following test:
All 10 variables data type test = OK (with gettype() function)
Variables data value = OK (printed all data value for checking)
Mysql query statement = OK (tested on MYSQL directly with inputted data, mysql is inserting values)
There is no syntax error either.
Variable alignment is = Ok
Data connection is = ok (as it runs other prepare statements without errors on same page)
Then where is the mistake?
I figure it out.
Solution:
It was not working because of the previous prepare statement $stmt_aff connection was not closed.
Once I closed it. Next Prepare statement $insert_stmt started working.
A good lesson learned why bind_param boolean error get produced if there are multiple prepare statement on the same page.
$stmt_aff->close();

Shorter way of binding too many variables in prepared statement

I am using the prepared statement for CRUD in PHP. My code snippet :
$SQL="INSERT INTO Dress(DressID, Description, Size, Price, EntryDate, CategoryID, ColorID)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE Description=?, Size=?, Price=?, EntryDate=?, CategoryID=?, ColorID=?";
$stmt=$connection->prepare($SQL);
$stmt->bind_param("ssssss", $ColorID, $Color, $Color);
Then, I have to repeat the variables binding in bind_param function, like bind_param("sssssssss", $var1, $var2, $var1, $var2, $var3..).
Is there any way to shorten this binding?
You can pass the parameters to the ->execute() method, like this:
$stmt->execute([123, 'red', 'green', ... ]);
If you keep the parameters in an array, instead of assigning them to variables, then binding them to the prepared statement can become rather trivial.

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

If I use $_POST value directly in bindParam (mysqli) will there be a security issue?

I have been reading about using $_POST values being used directly in isert statements and understand that this is an invitation for trouble. What is not clear in any of the posts I read was -
Say my form is sending 7 items to my mysqli insertion script and I use the posted values like this:
$stmt = $mysqli->prepare("INSERT INTO `advertisements` (`from`, `r_u_res`, `email`, `blockname`, `floorno`, `doorno`, `content`) VALUES (?, ?, ?, ?, ?,?,?)");
$stmt->bind_param('sssssss', $_POST['from'], $_POST['rures'], $_POST['email'], $_POST['blockname'], $_POST['floorno'], $_POST['doorno'], $_POST['content']);
$stmt->execute();
$stmt->close();
Would that be the correct way to do it? Or should I first store the posted values in a new variable and use that variable while binding? - like this :
$postedfrom = $_POST['from'];
$postedrures = $_POST['rures'];
$postedemail = $_POST['email'];
$postedblockname = $_POST['blockname'];
$postedfloorno = $_POST['floorno'];
$posteddoorno = $_POST['doorno'];
$postedcontent = $_POST['content'];
$stmt = $mysqli->prepare("INSERT INTO `advertisements` (`from`, `r_u_res`, `email`, `blockname`, `floorno`, `doorno`, `content`) VALUES (?, ?, ?, ?, ?,?,?)");
$stmt->bind_param('sssssss', $postedfrom, $postedrures, $postedemail, $postedblockname, $postedfloorno, $posteddoorno, $postedcontent);
$stmt->execute();
$stmt->close();
I saw a post OO mysqli prepared statements help please where the answer does seem to be like the code above but I want to know whether doing it like the first code poses security issues...
both forms are equivalent from a security perspective as php first resolves the values to be passed in the method call to $stmt->bind_param, thus that function sees the exact same values in both cases.
ps: both snippets look ok to me.

properly sanitize multiple user inputs with mysqli

Im currently using mysqli, and I want a way to properly sanitize every single user input. Im looking for the most simple lightweight way to do this, as I understand that Im NOT supposed to use mysql_real_escape....
my query is like so
$stmt = $sql->prepare("INSERT INTO Persons (msg, ip, time, main, twit, city, lat, lon, lang)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
as i understand i'm supposed to use the function bindParam... If i use it like so, am i completley securing my user inputs?
$stmt->bind_param('sssssssss', $_POST[msg], ('$ip'), ('$date'), '$_POST[main]', '$_POST[twit]', ('$cit'), ('$lat'), ('$lon'), '$_POST[lang]');
$stmt->execute();
$stmt->close();
If this isn't securing my user inputs how do i properly do so?
You need to prepare the statement to be safe. Something like below (its probably not 100% but gives you an idea)
$sql = new mysqli("localhost", "my_user", "my_password", "world");
$stmt = $sql->prepare("INSERT INTO Persons (msg, ip, time, main, twit, city, lat, lon, lang)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssssss",$_POST[msg], $ip, $date, $_POST[main], $_POST[twit], $cit, $lat, $lon, $_POST[lang]);
$stmt->execute();
First of all you have to follow basic PHP syntax
'$_POST[msg]' would be inserted as a literal $_POST[msg] string, while you expecting a value for $_POST['msg'] variable.

Categories