I have heard that using PREPARE and EXECUTE in a SQL statement will sanitize user-supplied data into something incapable of SQL injection. Is this true?
My original query is this:
$query =
"SELECT * FROM sales_orders
WHERE ksisoldby ILIKE '".$user."'";
This is my best guess for changing it to a prepare/execute statement:
<?php
$id = $_POST['id'];
$search = $_POST['user_supplied_search_term'];
PREPARE search_query_function (varchar, varchar) AS
SELECT * FROM sales_orders
WHERE ksisoldby ILIKE '$1'";
EXECUTE search_query_function($id, $search);
?>
Is this written/invoked correctly? There are also some built in php objects (PDO) that I have read about. Should I be using those instead or in conjunction? Thanks for help on this sort of broad question.
You incorporate prepare() and execute() in PHP by using prepared statements, which are available when you use PDO. This extensions is responsible for creating the appropriate PREPARE and EXECUTE statements for your database according to the database driver you have selected.
Here is an example adapted from the PHP manual using prepare() and execute().
$sth = $dbh->prepare('SELECT * FROM sales_orders
WHERE ksisoldby ILIKE ?');
$sth->execute( array( $_POST['user_supplied_search_term']));
This will take care of the parameter escaping for you and create an SQL statement similar to:
SELECT * FROM sales_orders
WHERE ksisoldby ILIKE 'something'
So you need to adapt the above code to include your SQL statement within the call to prepare(), which requires you to add placeholders to where you want your parameters to be included. Then you call execute(), which will add in the values passed to it.
You could also use pg_query_params, easy to use and safe.
Related
Hi all I need to use Prepared Statements in my site. I tried use this
$sql = "SELECT * FROM tbl_user WHERE uid=:id and activation_key=:key";
$query = $this->db->query(
$sql,
array( ':id' => $uid ,':key' => $activation_key)
);
but this is not working. When I change :id and :key to ? its working.
CodeIgniter does not support Prepared Statements. If you look at the sourcecode for CI's Database class, you will see that they resolve bindings simply by replacing the question marks with the data from the passed array:
https://github.com/EllisLab/CodeIgniter/blob/develop/system/database/DB_driver.php#L874
They only support Query Binding with unnamed placeholders. See http://ellislab.com/codeigniter/user-guide/database/queries.html
Query Bindings
Bindings enable you to simplify your query syntax by letting the system put the queries together for you. Consider the following example:
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
The question marks in the query are automatically replaced with the values in the array in the second parameter of the query function.
and http://ellislab.com/forums/viewthread/105112/#528915
Even though CI doesn’t support prepared statements, it does support Query Bindings. With prepared statements you have to call some type of prepare() function and then some type of execute() function. With query bindings, you only have to call one function and it basically does the same thing. Because of this, I like query bindings better than prepared statements.
On a sidenote, changing ? to :foo is merely changing from unnamed to named bindings (which CI apparently does not support either). Just because you use either or doesn't mean you are preparing the statements.
I came across this question as I faced a similar issue. The answer is correct that CI doesn't support prepared statements. However it doesn't mean that you can't use prepared statements!
In the following example I am using PDO as my connection class but the following code will work:
$q = $this->db->conn_id->prepare('SELECT * FROM tbl_user WHERE uid=? and activation_key=?');
$q->execute(array($param1,$param2));
print_r($q->fetchAll());
Note the conn_id is the PDO object against which you can run your prepared statements.
What this won't allow however is for you to get the query string which the native CI functions allow. You will need something like Get Last Executed Query in PHP PDO for that.
Further more however this doesn't stop you using the Query Builder to build your statements which you can then use in the PDO prepare. For example -
$db->where('uid = ?',null,false);
$db->where('activation_key = ?',null,false);
$q = $this->db->conn_id->prepare($db->get_compiled_select('tbl_user'));
Would build the query and would allow you to see the basic query if you output $db->get_compiled_select('tbl_user');
As #site80443 points out, CI4 now supports prepared statements and this can be found here:
https://codeigniter.com/user_guide/database/queries.html?highlight=prepared#prepared-queries
In my table i have query:
$sql="SELECT * FROM `jom_x1_organizatori`
WHERE Organizator='".$sta_dalje."' Order by `Struka`,`Zanimanje`";
$sta_dalje=$_POST["state_id"] from another table and value is:
ЈУ Гимназија са техничким школама Дервента
"ПРИМУС" Градишка
In case 1 working.
How to make query?
Firts of all: Never build the query by concatenating the query string with user input! If you do, then escape the input with the library's dedicated function (mysqli_real_escape_string for example). Without escaping you will open a potential security hole (called SQL injection).
"ПРИМУС" Градишка is not working because after concatenating, the query will be invalid. Now imagine, what happens, if I post the following input: '; DROP TABLE jom_x1_organizatori; --
Your query will be:
SELECT * FROM `jom_x1_organizatori`
WHERE Organizator=''; DROP TABLE jom_x1_organizatori; --' Order by `Struka`,`Zanimanje`
Whenever you can use prepared statements to bind parameters (and let the library to do the hard work), but always escape and validate your input (using prepared statements, escaping is done by the library)!
$sta_dalje = (sting)$_POST["state_id"]; // Do filtering, validating, force type convertation, etc!!
// Prepare the statement (note the question mark at the end: it represents the parameter)
$stmt = $mysqlLink->mysqli_prepare(
"SELECT * FROM `jom_x1_organizatori` WHERE Organizator = ?"
);
// Bind a string parameter to the first position
$stmt->bind_param("s", $sta_dalje);
For more info about prepared statements:
mysqli prepared statements
PDO prepared statements
Please note that the old mysql extension is deprecated, do not use it if not necessary!
Just a side note
Do not use SELECT * FROM, always list the columns. It prevents to query unnecessary data and your code will be more resistant to database changes, plus debugging will be a bit simplier task.
Use escape string
$sta_dalje = mysqli_real_escape_string($con, $_POST["state_id"]);
And your where condition can be simply
Organizator='$sta_dalje'
I am new to the PDO class, I have been using MYSQLI since just now and I am kind of confused. This question is rather simple but I cannot find the answer in straight text anywhere in the manual. So calling $pdo->query(some query) will automatically escape the query and will not leave any room for potential injections of any kind. Is this true?
NO, this is NOT true.
To avoid any risk of mysql injections you will need either prepared statments or to escape properly your variables (which would involve you to manually escape each variable before submit). I would suggest to use prepared statements because they are way easier to use. Please read this post How can I prevent SQL injection in PHP?. You can either have those with mysqli OR PDO, a nice example of PDO prepared statments, token from stackoverflow
$id = 1;
$stm = $pdo->prepare("SELECT name FROM table WHERE id=?");
$stm->execute(array($id));
$name = $stm->fetchColumn();
You can learn more here about PDO prepared statements. I would also like you to have a look here How can prepared statements protect from SQL injection attacks?
the query function is not safe.
you better use prepare of the PDO object.
e.g.
$sth = $dbh->prepare("select * from mytable where myattr = :attr");
the $sth handler can be used to set the placeholder in your query (e.g. :attr in this example)
you have two choice :
either you use an array directly in the execute function of the handler :
$sth->execute (array ('attr', $myattr));
or the bindParam function of the handler then execute
$sth->bindParam ('attr', $myattr);
$sth->execute();
The method provide a good way of escaping the single quotes in your arguments.
note : also take a loot at Why you Should be using PHP’s PDO for Database Access (net.tutsplus.com)
No, PDO::query is just as vulnerable as mysql_query or any other raw query method.
If you do
$sql = "SELECT foo FROM bar WHERE baz = '$var'";
and $var is
Robert'; DROP TABLE users; --
so the result is
SELECT foo FROM bar WHERE baz = 'Robert'; DROP TABLE users; --'
then no API can help you, because no API can tell the difference between what the query part and what the user value is. This difference is only clear to the API when you use prepared statements or escape special characters in the value properly.
Read The Great Escapism (Or: What You Need To Know To Work With Text Within Text).
Are all 3 options the same (Y/N) or is one better (A/B/C)?
Option A - (1) defining the SQL string in the variable $sql and (2) define the statement handle using the "method" prepare on the variable $sql to compose the statement and (3) activating composition of the statement in step 2 using the execute function.
$sql = "SELECT * FROM table1";
$sth = $dbh->prepare($sql);
$sth->execute();
Option B - Similar to Option C because the ->query method is used directly on the db object and similar to Option A in that the sql statement is kept separate.
$sql = "SELECT * FROM table1";
$sth = $dbh->query($sql);
Option C - The statement handle is the sql query itself (no reference to any another variables and just using one method.
$sth = $dbh->query("SELECT * FROM table1");
Questions:
Do both options yield the same result?
If they yield the same result, is one approach recommended (i.e. best practice)?
Did I get the vocabulary like "variable", "method", and "function" correct?
Does Option A still query the db despite not explicitly using the ->query() method?
What are the pros/cons of including the sql stmnt in a seperate variable vs in the PDO Statement?
I would say both methods are the same about using a string variable or direct text string.
Assuming you using PDO there is difference between prepare statement and invoke a query statement.
In case A, the prepare statement will make the database create a plan so that statement can be reexecuted without reparsing the query string.
In case B the query is executed at once.
In your given example case B would run a little bit faster.
But if your statement uses arguments case A would benefit you with additional security due to placeholders been replaced by the driver.
Do both options yield the same result?
Yes.
If they yield the same result, is one approach recommended (i.e. best practice)?
Both are fine. In your particular example Option B gets the same job done with less code.
However, if you need to use parameters and/or constraints in your query (e.g. ...WHERE id = :id) you need to opt for option A to bind params using the $dbh->bindParam(':id', $id, PDO::PARAM_INT) method after your prepare your statement, e.g:
$dbh->prepare('UPDATE table SET column = :value WHERE id = :id');
$dbh->bindParam(':value', $someNewValue, PDO::PARAM_STR);
$dbh->bindParam(':id', $targetId, PDO::PARAM_INT);
$dbh->execute();
Doing it this way will also protect you from nasty things like SQL injections.
Storing the query in a separate variable is only needed if you plan to re-use that query at a later time in your code. Otherwise you might as well just type it within your prepare/query method directly.
Did I get the vocabulary like "variable", "method", and "function" correct?
Looks about right! Except: "the execute function" is a method. Functions and methods are basically the same things except when they belong to an object they are referred to as methods. In your example execute belongs to the $sth object, so it's called a method.
Does Option A still query the db despite not explicitly using the ->query() method?
Yes. The execute method executes the query that was prepared in $dbh->prepare(...). If you want to use parameters you can call ->bindParam() between your prepare and execute methods. If you don't need parameters, invoking ->query() directly is really the more convenient way to do it.
I had the following piece of code with PDO prepared statements:
$stmt = $conn->prepare('SELECT `myColumn1` FROM my_table '.
'WHERE `myColumn2`=:val LIMIT 1');
$stmt->bindValue(":val", $value);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
This works fine. It sends the following query:
113 Query SELECT `myColumn1` FROM my_table WHERE `myColumn2`=":val" LIMIT 1
and it returns the correct value.
But it doesn't work if I change the first line to
$stmt = $conn->prepare('SELECT `myColumn1` FROM my_table '.
'WHERE `myColumn2`=":val" LIMIT 1');
or
$stmt = $conn->prepare('SELECT `myColumn1` FROM my_table '.
'WHERE `myColumn2`=':val' LIMIT 1');
The same query is sent, but PDO returns false.
Can anybody explain why?
From the page you quote:
The parameters to prepared statements don't need to be quoted; the driver automatically handles this.
The purpose of the quotation marks is to delimit string data from the rest of the query, since it cannot easily be separated (unlike numbers, which have an obvious format). Since using prepared statements means that query and data are passed separately, the quotes are unnecessary.
One of the advantages of prepared statements are that types are handled for you (sort of...). In other words, prepared statements allow MySQL (or whatever RDBMS) to decide how to handle data. When putting quotes, that would force it to be a string which doesn't make sense. If it's supposed to be a string, then the server will handle that.