' OR '1'='1 is a universal SQL injection statement. It can easily alter the logical relationships within an SQL statement, causing it to deviate from its original intended effect, such as bypassing user password authentication.
Assume the following user information table exists:
| id | username | password |
|---|---|---|
| 1 | admin | 123456 |
The following SQL statement is used to verify whether the username and password are correct. If correct, the query returns a result; if incorrect, the query returns no result, indicating an incorrect username or password:
SELECT id FROM test.user
WHERE username='admin' and password='123456';
When the entered username is admin and the password is 123456, a query result exists, indicating the username and password are correct.
However, you should never trust user input. A user can construct special values to achieve SQL injection, altering the intended effect of the original statement. Observe:
SELECT id FROM test.user
WHERE username='admin' and password='' OR '1'='1';
When the password value is ' OR '1'='1, the WHERE condition of this SQL statement becomes always true due to OR '1'='1', causing it to return the id of all users in the table, completely bypassing the username and password verification.
This is a classic example of bypassing username and password authentication through SQL injection!
How to Prevent SQL Injection
Never trust user input. Validate and filter user input, and use parameterized queries.
Do not use string concatenation to combine SQL statements with input values.