When to use mysqli_real_escape_string?
14,042
You should use mysqli_real_escape_string for any data that comes from the user or can't be trusted.
Author by
jaypabs
Updated on June 04, 2022Comments
-
jaypabs about 2 years
Possible Duplicate:
Best way to prevent SQL Injection in PHPI 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?
-
jaypabs almost 12 yearshi, i am actually using prepared statement on my other script but since i have ported most of my script from mysql to mysqli i have a lot of sql statement that is using a traditional programming. so instead of using prepared statement, i decided to use mysqli_query instead of modifying all my code to use prepared statement. so for the meantime is it safe to use code like:
mysqli_real_escape_string($_POST['username'])
? -
jaypabs almost 12 yearsyou mean i have to use mysqli_real_escape_string even in the value of the update statement like:
$query = "UPDATE foo set bar = mysqli_real_escape_string($_GET['var']) ..."
and also in WHERE clause like:$query = "SELECT bla from foo WHERE bar = mysqli_real_escape_string($_COOKIE['var'])"
? -
David Barker almost 12 years@jaypabs yes you can use it like that, and it will provide a level of security, however it doesn't escape strings that contain special chars:
%
and_
that are used in LIKE clauses. As they are usually contained within double quotes in the query they are still a risk. (see ammended info in my answer) -
jaypabs almost 12 yearsdoes this mean that we really have to use prepared statement? what happened to
mysqli_query
? ismysqli_query
already useless? -
David Barker almost 12 yearsPrepared statements provide you with a much more robust defense than mysqli or mysql could ever do out of the box. Managing all user inputted data in the fashion described above gets very tedious indeed. And, I wouldn't say
mysqli
was dead, but it is certainly the least preferred choice. -
David Barker almost 12 yearsWorth mentioning that whether you're using PDO or not you should also always use 'htmlspecialchars()` as well (php.net/manual/en/function.htmlspecialchars.php) when inputting into a db