简体   繁体   中英

mysql_real_escape_string() not sanitizing variable

I'm working on an existing website trying to prevent SQL injections. Before $_GET['ID'] was unsanitized.

$ID=mysql_real_escape_string($_GET['ID']);
$sQuery=mysql_query("select * from tbl_mini_website as s1, tbl_actor_merchant as me where s1.MERCHANT_ID=$ID AND s1.MERCHANT_ID=me.MERCHANT_ID");

If I put a ' at the end of the url, with mysql_real_escape_string() I get this from mysql_error() :

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\\\\' AND s1.MERCHANT_ID=me.MERCHANT_ID' at line 1

with out mysql_real_escape_string() I get:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\\' AND s1.MERCHANT_ID=me.MERCHANT_ID' at line 1

I'm not sure whats up with it? Any help would be greatly appreciated.

If it is an id, numerical I assume, why don't you just cast it to an integer?

$ID = (int) $_GET['ID'];

The best advice I can give you is to check out PDO and use bound parameters.

mysql_real_escape_string escapes, but doesn't quote.

Try:

$sQuery=mysql_query("select * from tbl_mini_website as s1, tbl_actor_merchant as me where s1.MERCHANT_ID='$ID' AND s1.MERCHANT_ID=me.MERCHANT_ID");

More generally, I tend to wrap both of these in a function, like:

function quoteValue($value) {
    return "'" . mysql_real_escape_string($value) . "'";
}

This is useful, because you may find down the line that you want more refined quoting behavior (especially when it comes to handling Unicode, control characters, etc.)

It's because you're not quoting the variable.

Here's your query given the following inputs

$_GET['ID'] = "1";
$ID=mysql_real_escape_string($_GET['ID']);
SELECT ... where s1.MERCHANT_ID=1 ...

$_GET['ID'] = "1'"
$ID=mysql_real_escape_string($_GET['ID']);
SELECT ... where s1.MERCHANT_ID=1\' ...

$_GET['ID'] = "1'"
SELECT ... where s1.MERCHANT_ID=1' ...

Phil Brown is right, but you shoul forget about old fashioned mysql_real_escape_string or mysql_connect() as they are very old and move to php`s PDO() where you cand use prepared statements, binds, fetch object any many many more functions.

I suggest read PDO documentation at http://php.net/manual/en/book.pdo.php if you want next generation dabatase manipulation and security from SQL Injection .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM