This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
<?php
// I fetching data from sql table "product".i want to prevent all unwanted characters and all.please add your suggestions in my code.
if(isset($_GET['search'])){
$search_query = $_GET['user_query'];
$get_pro = "select * from product where title like '%$search_query%'";
$run_pro = mysqli_query($con, $get_pro);
while($row_pro=mysqli_fetch_array($run_pro)){
$pro_title = $row_pro['title'];
echo " <span>$pro_title</span> "
}
}
?>
To prevent SQL Injection PDO(PHP Data Objects) is the best way to go. PDO gives more flexibilty to the programmer as if you want to switch your project to use another database, PDO makes the process very easy. You only have to change the connection string and a few queries.
If your project is in initial stage and you want to attain more flexibility I'll highly recommend to switch over to PDO. To know more about PDO you can refer to this link How does PHP PDO's prepared statements prevent sql injection? What are other benefits of using PDO? Does using PDO reduce efficiency?
Okay coming back to the problem you asked. To prevent SQL injection in mysqli interface you could use mysqli_real_escape_string() function which takes two args:
connection- Specifies the MySQL connection to use(required)
escapestring- The string to be escaped(required)
After this step your code will look like this-
$search_query = mysqli_real_escape_string($conn, $_GET['user_query']);
where $conn will be your connection handle.
You can append the '%' operator after this step and can use the result to perform the query.
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I have this mysql query:
$sql = "INSERT INTO lijsten(naam, niveau, nederlands, duits, frans, grieks,
engels, latijn, spaans, wiskunde, natuurkunde, scheikunde, geschiedenis,
economie, aardrijkskunde, ANW, godsdienst)
VALUES(\$_POST["naam"]\,\$_POST["niveau"]\,\$_POST["nederlands"]\,\$_POST["duits"]\,\$_POST["frans"]\,\$_POST["grieks"],\$_POST["engels"]\,\$_POST["latijn"]\,\$_POST["spaans"]\,\$_POST["wiskunde"]\,\$_POST["natuurkunde"]\,\$_POST["scheikunde"]\,\$_POST["geschiedenis"]\,\$_POST["economie"]\,\$_POST["aardrijkskunde"]\,\$_POST["ANW"]\,\$_POST["godsdienst"]\)";
It is sent to the database with this function:
function connectDB($sql) {
$DBcon = mysql_connect(host, user, pass) or die(mysql_error());
mysql_select_db(database);
$result = mysql_query($query) or die(mysql_error());
mysql_close($DBcon);
return $result;
But when i try to run it, it gives me a php parse error:
PHP Parse error: syntax error, unexpected 'naam' (T_STRING) in /media/usbdisk/website/www/boeken/naardb.php on line 11
Could somebody tell me what mistake i am making? I already have tried many ways of putting the query, but none of them worked.
You should never build queries like this.
This is not how you escape values
mysql_ is deprecated and you should be using prepared statements
Example in PDO:
$sql = "INSERT INTO lijsten(naam, niveau, nederlands, duits, frans, grieks,
engels, latijn, spaans, wiskunde, natuurkunde, scheikunde, geschiedenis,
economie, aardrijkskunde, ANW, godsdienst)
VALUES(:naam,:niveau .......)";
if($stmt = $pdo->prepare($sql)){
$stmt->bindValue(:naam, $_POST["naam"]);
.....
$stmt->execute();
}
There are several mistakes, but I'll start with the issue.
unexpected 'naam' (T_STRING)...
Is caused because PHP was not expecting a string there. You're escaping parts of the query, but you really just need to concatenate the $_POST variables.
I would advise setting the posts variables to their own variables to simplify your query and format the query like this answer outlines: Using php variables inside MySQL insert statement
IE: $naam = $_POST["naam"]; etc...
The biggest issue is that you're using a deprecated method, you should use PDO (Prepared) queries
PHP deprecated methods.
You should definitely look into using PDO and preparing your statement.
A couple quick reference for PDO:
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
http://php.net/manual/en/book.pdo.php
Good luck!
Try to concat the variables in your query like this:
"INSERT INTO lijsten(naam, niveau, nederlands, duits, frans, grieks,
engels, latijn, spaans, wiskunde, natuurkunde, scheikunde, geschiedenis,
economie, aardrijkskunde, ANW, godsdienst)
VALUES("
.mysql_escape_string($_POST['naam']).
")";
and to read about sql injections too.
The #meda answer is the correct example of how to create SQL calls, using PDO.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
I need some help and very very fast because my database was injected. I need at least a script that won't allow users to use :[Spaces, Sybols like ('*','=','/','.') and a list of words ('SELECT','FROM','WHERE')] in the text fields of my register form.
I heared something about mysql_real_escape_string(). What is this command doing? And don't post links to PHP: mysql_real_escape_string() Manual because I already read that.
There'a a right and a wrong way to approach this. The (usually) wrong way is to try and set up an input sanitation method (like a script) and hope that nothing gets through. It usually doesn't work.
What I recommend you to do is rewrite your PHP SQL queries to use MySQLi prepared statements. These are queries that are first converted from the common SQL syntax ("SELECT... WHERE...") to a statement your engine can work with, and only then are the fields replaced with your input, thus preventing SQL injection.
For example, the (very) susceptible SQL syntax:
"SELECT * FROM users_passwords WHERE user='" + user + "' AND pass='" + password + "'"
Can be converted to the following prepared statement:
"SELECT * FROM users_passwords WHERE user=? AND password=?"
And then, using the command bind_param(), you can safely replace the ? placeholders with your parameters after the statement is prepared. While the original SQL query allows you to use some basic injection techniques (like writing ' OR true OR '), prepared statements will not allow this.
Here's a working example:
// Create a new MySQLi connection object
$db = new mysqli('localhost','db_username','db_password','db_name');
// Create a new prepared statement
$stmt = $db->prepare('SELECT * FROM users_passwords WHERE user=? AND pass=?');
// Bind the parameters, in order, to the statement (s stands for string)
$stmt->bind_param('ss', username, password);
// Self-explanatory
$stmt->execute();
If you are in PHP then why don't you do it in your PHP script. sanitize all your user provided input in GET and POST and then move it forward to DB calls. That is the right way to do it.
I would strongly avoid constructing SQL query strings from any input even if you sanitize it.
The good way for security purposes and performance is to use functions to set the parameters:
for example:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
see http://php.net/manual/en/pdo.prepared-statements.php
This question already has answers here:
Why is PDO better for escaping MySQL queries/querystrings than mysql_real_escape_string?
(6 answers)
Closed 9 years ago.
$q = "INSERT INTO articles VALUES( mysql_real_escape_string($_GET["article"]) )
$req = $bdd->prepare($q);
$req ->execute();
I've been working on another server where mysql_real_escape_string() is still not obsolete, and now I'm moving the site to another mysql server which apparently doesn't accept this function anymore. And, it's pretty clear I need to use some PDOs
SO what's the PDO equivalent for mysql_real_escape_string()? I'm trying something like this
$idc = new PDO(...);
$q = "INSERT INTO articles VALUES( $idc->quote(($_GET["article"])));
$req = $bdd->prepare($q);
$req ->execute();
I do use prepared statements, but I suspect my PDO::quote is wrong somewhere.
But it doesn't render the same result...
Thank you.
PDO::quote is the equivalent of mysql_real_escape_string. If there's some reason you can't use a prepared statement, you can use it like this:
$q = "INSERT INTO articles VALUES (" . $idc->quote($_GET["article"]) . ")";
A significant difference is that it includes the surrounding quotes around the string, while mysql_real_escape_string doesn't (so you would have to put quotes in your INSERT string).
Use prepared statements(preferred) or PDO::quote()
This question already has answers here:
Are PDO prepared statements sufficient to prevent SQL injection?
(7 answers)
Closed 9 years ago.
I am new to PDO. As I heard PDO can prevent SQL injection attack.
Here's what I have written:
$db = new PDO('mysql:host=192.168.57.36; dbname=somedb; charset=UTF8', 'user1', 'pass1');
$sql = "SELECT * FROM table1 WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($tid));
Is it a secure code ? I guess prepared should do some securing acts but the variable is passed to query after it.
Shoud I use addParam before execution method?
Thank you.
Shoud I use addParam before execution method?
No.
Passing a variable into execute does pretty the same.
There could be other issues though, you can read on them here