Possible Duplicate:
Best way to prevent SQL Injection in PHP
I am wondering about sql injection and want to know when to use mysqli_real_escape_string.
Do I need to use it every time I have a WHERE clause in my query?
Possible Duplicate:
Best way to prevent SQL Injection in PHP
I am wondering about sql injection and want to know when to use mysqli_real_escape_string.
Do I need to use it every time I have a WHERE clause in my query?
You should use mysqli_real_escape_string for any data that comes from the user or can't be trusted.
You have to use it when you include $_REQUEST "vars" in your query eg.
$query = "UPDATE foo set bar = '{$_GET['var']}' ..."
$query = "INSERT INTO foo ('{$_POST['var']}',) ..."
$query = "SELECT bla from foo WHERE bar = '{$_COOKIE['var']}'"
each of this querys must be mysqli_real_escape_string to provide injections ...
You use mysqli_real_escape_string
or any variation of it to make sure data form any user input field is properly escaped.
For example, you have a form with a few inputs. You click submit and the data is sent as a request to your PHP script. In your script you insert into a database the values the user posted.
If a user typed the following into an input field on user login for example:
' WHERE `username` = {x} AND password > 1;
There is potential for that person to have all of the data from the table you are working with. Using:
mysqli_real_escape_string($input)
Would yield the above as:
\' WHERE `username` = {x} AND password > 1;
The escape string on the ' would stop a possible SQL injection attack from working.
That said there is no reason you should be using mysqli_real_escape_string()
as the PDO and bound parameters are far superior at deflecting a host of different SQL attacks / injection methods. Learn it and use it!
Edit due to comments
%
and _
will also need special treatment above and beyond mysqli_real_escape_string()
function escape_extra_chars ( $string )
{
$string = preg_replace("/\%/", "\%", $string);
$string = preg_replace("/\_/", "\_", $string);
return $string;
}
Along those lines anyways (that func is untested)