I came across the above injection and I can not figure out why(how) does this work and what's interesting is it returns all the records from the database.
Anything guys? educate me
It runs the query
WHERE id=id. As
id is just another column and in SQL you can just pass name of column when doing comparison operations.
This is saying to fetch all rows WHERE
id of the row equals
id of the same row, which is true for all rows.
This is same as
WHERE 1=1, it basically alters
WHERE statement in such a way that it is always true.
The injected fragment probably results in a query similar to this:
… WHERE id=id=2-1
Since MySQL is parsed from left to right, the above is equivalent to:
… WHERE (id=id)=2-1
… WHERE 1=2-1
Which, oft course, can be simplified to:
… WHERE 1=1
And this, again, is true for each row with a non-
Regarding the title: it’s a common misunderstanding that passing an input value through
mysql_real_escape_string function makes it automatically safe to be used in an SQL statement. Even the PHP manual states that ambiguous:
This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.
However, what the manual is missing is that values passed through
mysql_real_escape_string are only supposed to be used in MySQL string literals and nowhere else. Unfortunately, the manual misses to clarify that important aspect.
Likewise, in the case discussed above, the input value is not used in a string literal, so
mysql_real_escape_string won’t help. However, a prepared statement, in which the input would be passed as parameter, would have helped.