When should I use prepared statements exactly? - php

I want to know, can I just use prepared statements one time?
Here is my script:
$stm = $db->prepare("UPDATE
qanda AS ans1
JOIN qanda AS ans2 ON ans2.related = ans1.related
JOIN qanda AS ques ON ans2.related = ques.id
SET ans1.acceptedanswer = 1,
ans1.aadate = IF( ans1.id <> ?, ans1.aadate, ?)
WHERE ques.author_id = ? AND ans2.author_id = ?
");
$stm->execute(array($answer_id, time(), $_SESSION["Id"], $author_id));
$done = $stm->rowCount();
if ($done){
/* I don't use prepared statement here */
$stm1 = $db->prepare("UPDATE user SET rep = rep + 15 WHERE id = $author_id");
$stm1->execute();
}
As you see I didn't use prepared statement for second query. Because I did it for first query and if first query is working then I'm sure arguments are valid and don't need to bind them by prepared statement.
Please don't ask me why you don't want to use prepared statemen't for second query, because the reason is too long.
So what I'm doing is correct? Isn't there any security problem?

The straight answer is: yes, you can.
The reason why is actually up to you, since it's anyway good practice to use prepared statement whenever you pass values.
Also consider that, if you are not binding any parameter, it makes more sense to use the query() method, just to be explicit on the fact that you are not going to bind anything. So your second query would be
$stm1 = $db->query("UPDATE user SET rep = rep + 15 WHERE id = $author_id");
(see http://php.net/manual/en/pdo.query.php)
instead of
$stm1 = $db->prepare("UPDATE user SET rep = rep + 15 WHERE id = $author_id");
$stm1->execute();
Moreover you mentioned a dynamic query, but this is not the case of your sample code. Anyway I will give you an example of how two use prepared statement also on queries dynamically generated.
It's a silly example, but should be enough to give you an idea.
Assume we have some values to update 'email', 'date_of_birth' and 'website'. Let's say we want to do some check on this data before inserting them. I'll pretend we have a valid() function already in place.
$dynamic_sql = array();
$parameters[':date_of_bird'] = $date_of_birth;
if(valid($email)) {
$dynamic_sql['email_sql'] = "email = :email";
$parameters[':email'] = $email;
}
if(valid($website)) {
$dynamic_sql['website_sql'] = "website = :website";
$parameters[':website'] = $website;
}
if(count($dynamic_sql)>0) {
$dynamic_sql = ','.implode($dynamic_sql);
}
$query = "UPDATE user
SET date_of_birth = :date_of_birth $dynamic_sql
WHERE
user_id = :user_id";
$stm = $db->prepare($query);
$stm->execute($parameters);
This kind of approach will allow you to keep using prepared statement also with dynamically generated SQL.

Related

Using PHP variable in SQL query

I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.

MySQLi prepared Conditional Statements

I have four possible variables, only one of them is required. My question is, how do I prepare a statement / construct the sql query if there parts of the query that may or not show up.
Something like this, I guess:
sql = "SELECT * FROM dogs WHERE name = ?"
if(isset($dogid)) {
sql .= "AND WHERE id = ?";
}
}
if(isset($dogcolour)) {
sql .= "AND WHERE colour = ?";
}
My brain is totally broken, and I figure there has to be a better way to prepare it than using something like $dogID = "true"; in each if, and then binding it at the end with a bunch of if statements.
Well I would define some empty value, and then check everything in database.
$sql = "SELECT * FROM dogs WHERE (IF(? = 0, 1 = 1, name = ?)) AND (IF(? = 0, 1 = 1, colour = ?))"
this solution has one drawback, you need to pass all parameters twice:
$statement->bind_param('ssss', $name, $name, $colour, $colour);
if name or $colour variable is 0 then 1 = 1 is executed in where statement (witch is always true). There should be posibility to pass NULL value to mysqli, however for me it doesn't work, if it work then could be possible to simplify query.
$sql = "SELECT * FROM dogs WHERE name = (IFNULL(?, name)) AND colour = (IFNULL(?, colour))"

mysqli prepared statement without bind_param

I have this code for selecting fname from the latest record on the user table.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$sdt=$mysqli->('SELECT fname FROM user ORDER BY id DESC LIMIT 1');
$sdt->bind_result($code);
$sdt->fetch();
echo $code ;
I used prepared statement with bind_param earlier, but for now in the above code for first time I want to use prepared statement without binding parameters and I do not know how to select from table without using bind_param(). How to do that?
If, like in your case, there is nothing to bind, then just use query()
$res = $mysqli->query('SELECT fname FROM user ORDER BY id DESC LIMIT 1');
$fname = $res->fetch_row()[0] ?? false;
But if even a single variable is going to be used in the query, then you must substitute it with a placeholder and therefore prepare your query.
However, in 2022 and beyond, (starting PHP 8.1) you can indeed skip bind_param even for a prepared query, sending variables directly to execute(), in the form of array:
$query = "SELECT * FROM `customers` WHERE `Customer_ID`=?";
$stmt = $db->prepare($query);
$stmt->execute([$_POST['ID']]);
$result = $stmt->get_result();
$row = $result->fetch_assoc();
The answer ticked is open to SQL injection. What is the point of using a prepared statement and not correctly preparing the data. You should never just put a string in the query line. The point of a prepared statement is that it is prepared. Here is one example
$query = "SELECT `Customer_ID`,`CompanyName` FROM `customers` WHERE `Customer_ID`=?";
$stmt = $db->prepare($query);
$stmt->bind_param('i',$_POST['ID']);
$stmt->execute();
$stmt->bind_result($id,$CompanyName);
In Raffi's code you should do this
$bla = $_POST['something'];
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$stmt = $mysqli->prepare("SELECT `fname` FROM `user` WHERE `bla` = ? ORDER BY `id` DESC LIMIT 1");
$stmt->bind_param('s',$_POST['something']);
$stmt->execute();
$stmt->bind_result($code);
$stmt->fetch();
echo $code;
Please be aware I don't know if your post data is a string or an integer. If it was an integer you would put
$stmt->bind_param('i',$_POST['something']);
instead. I know you were saying without bind param, but trust me that is really really bad if you are taking in input from a page, and not preparing it correctly first.

unable to execute update statement in while loop php mysqli

I have the following query
$products = $this->mysqliengine->query("select * from temp_all_product where download_status = 0") or die($this->mysqliengine->error());
$temp_status_update = $this->mysqliengine->prepare("update temp_all_product set download_status = ? where id = ?") or die($this->mysqliengine->error);
$temp_status_update->bind_result($download_status, $id);
while($product = $products->fetch_assoc()) {
$id = $product['id'];
$download_status = 1;
$temp_status_update->execute();
}
In the above statement I can select the values from temp table but unable to update the status. What is the problem here
You need to use bind_param in your update statement instead of bind_result.
$temp_status_update->bind_param('dd', $download_status, $id);
The 'dd' just tells the system that each input is a number.
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
#eggyal was merely suggesting that you could replace all your code with a single update statement. Your remark about LIMIT does not make much sense.
Suggestion: If you don't have much invested in mysqli then switch to PDO. It allows using named parameters which can make your code more robust and easier to maintain:
$sql = "UPDATE temp_all_product SET download_status = :status where id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(array('status' => 1, 'id' => $product['id']));
Plus you can configure it to throw exceptions so you don't need all this error checking.
http://www.php.net/manual/en/book.pdo.php
http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/

Best way to avoid preparing the same PDO statement more than once?

Currently I save prepared statements into a private variable, because I ignore how they really work in the deepness, and do it just in case.
So the question is really simple, if I iterate over the same $PDO->prepare(), will it prepare again the same query?
foreach( $arr as $docid ) {
if( $this->dbLink === null ) { // PDO resource, saved in the object.
throw new Exception( 'Must first connect to DB' );
}
if( $this->queryCheckAccess === null ) {
$query = 'SELECT * from something where id = :id';
$this->queryCheckAccess = $this->dbLink->prepare($query);
}
else {
$result = $this->queryCheckAccess->execute(array(':id'=>$docid));
}
}
Will it matter ? Or the DB Engine / PHP is smart enough to know that it is the same prepared statement?
Thanks a lot.
----------------- EDIT --------------
I think I was misunderstood.
What I ask is what happens if I do:
$query = 'SELECT * from something where id = :id';
$this->queryCheckAccess = $this->dbLink->prepare($query);
$query = 'SELECT * from something where id = :id';
$this->queryCheckAccess = $this->dbLink->prepare($query);
$query = 'SELECT * from something where id = :id';
$this->queryCheckAccess = $this->dbLink->prepare($query);
$query = 'SELECT * from something where id = :id';
$this->queryCheckAccess = $this->dbLink->prepare($query);
And what happens if I do:
if( $this->queryCheckAccess === null ) {
$query = 'SELECT * from something where id = :id';
$this->queryCheckAccess = $this->dbLink->prepare($query);
}
Will the engine prepare the query 4 times in the first example? Or will notice it is the same query and just "jump" that?
Your code only prepares the query once, because after the first loop iteration, it's not NULL so it the conditional block won't run. But it's a waste of time to check the condition every time through the loop.
But to answer your question, if you prepare() the same query, it does do redundant work, even if the query is identical to the one you prepared before. So you should avoid that.
But you don't need to prepare inside the loop at all. Prepare once before you start the loop, and bind a variable to the parameter. You don't need to bind every time in the loop, just change the value of that variable.
if( $this->dbLink === null ) { // PDO resource, saved in the object.
throw new Exception( 'Must first connect to DB' );
}
$query = 'SELECT * from something where id = :id';
$this->queryCheckAccess = $this->dbLink->prepare($query);
$this->queryCheckAccess->bindParam(':id' => $docidparam);
foreach( $arr as $docid ) {
$docidparam = $docid;
$result = $this->queryCheckAccess->execute();
}
I'm not sure if you can bind the variable and also use it as the loop variable, there might be a scope conflict.
Another suggestion for this query: why not just run one query to search for a list of values?
$list = implode(",", array_fill(1, count($arr), "?"));
$query = "SELECT * FROM something WHERE id IN ( $list )";
$this->queryCheckAccess = $this->dbLink->prepare($query);
$this->queryCheckAccess->execute($arr);
PS: Also you should check for errors. If you enable PDO error mode EXCEPTION, then errors will automatically throw exceptions. If you don't enable that mode, you need to check the return value of prepare() and execute(), which return false if there's an error.
I just RUN a code similar to your example, and enabled MySQL Query LOG I found that all prepare requests are sent to MySQL Server
Prepare SELECT * FROM test_table WHERE username = ?
Close stmt
Prepare SELECT * FROM test_table WHERE username = ?
Close stmt
Prepare SELECT * FROM test_table WHERE username = ?
Close stmt
Prepare SELECT * FROM test_table WHERE username = ?
Close stmt
Test code:
$sth = $dbh->prepare($sql);
$sth = $dbh->prepare($sql);
$sth = $dbh->prepare($sql);
$sth = $dbh->prepare($sql);
$sth = $dbh->prepare($sql);
$sth->bindParam(1, $user);
$sth->execute();
Then, the best way is to prepare once, and Bind different values and then execute.
$sth = $dbh->prepare($sql);
$user = "test";
$sth->bindParam(1, $user);
$sth->execute();
$user = "test2";
$sth->bindParam(1, $user);
$sth->execute();
$user = "test";
$sth->bindParam(1, $user);
$sth->execute();
No, that's one of the main features of prepared statements. If you're going to run the same query multiple times but with different variables then preparing the query will give you a speed increase. Especially if you make use of transactions (requires InnoDB storage engine).
To answer the question from the title (which is quite different from questions in the body), the best way to avoid preparing the same statement more than once, apparently would be to avoid running multiple similar queries at all.
To answer the question from the question body - no, DB Engine / PHP is not "smart" enough to know that it is the same query were prepared again. With every new prepare() call another statement is created. And I would be first to hate such a "smart" behavior. The "smarter" your tool, the more unpredictable results you get.
To answer the real problem in the code, a smart developer would use a right tool to save himself a trouble.
With safeMysql whole mess will be reduced to one query and one line of code
$data = $this->dbLink->getAll('SELECT * from somth where id IN (?a)', $arr);
S0 - no multiple queries, no multiple preparations, no multiple questions.
By the way, you are losing first id with your code.
Yet you're losing all of them but last one if you don't use the result in place.

Categories