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


2 Answers 2


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

So the expression id=id is evaluated first and returns 1 (TRUE value) for each row as any non-NULL value is equivalent to itself when using the = operation. So it can be simplified to:

… 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-NULL id value.

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.

The result is that mysql_real_escape_string is also used for data which is not intended as a string literal. Like as a different literal value, a keyword, or even as a column or table identifier.

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.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .