Most websites keep their data in a database and talk to it using SQL. SQL injection happens when the app puts your input straight into a query, so your input becomes part of the command.
Practise only in your lab. Testing SQL injection on websites without permission is illegal.
Why it works
Imagine the app runs this, with your input in place of $id:
SELECT first_name, last_name FROM users WHERE user_id = '$id';
Type 1 and you get user 1. Now type 1' OR '1'='1. The query becomes:
SELECT first_name, last_name FROM users WHERE user_id = '1' OR '1'='1';
'1'='1' is always true, so the database returns every user.
Try it in DVWA
- Open
http://192.168.56.102/dvwa/from Kali and log in withadmin/password. - Go to DVWA Security, set it to low and submit.
- Open SQL Injection. Enter
1and note the result. - Enter a single
'. An SQL error appears, which is a strong sign the input reaches the query unchanged. - Enter
1' OR '1'='1and watch every user appear.
The real fix: parameterised queries
Instead of building the query as text, the app sends the query and the input separately. The database then treats the input as data, never as code.
cur.execute("SELECT first_name FROM users WHERE user_id = %s", (user_id,))
$stmt = $pdo->prepare("SELECT first_name FROM users WHERE user_id = ?");
$stmt->execute([$id]);
With this, 1' OR '1'='1 is just a strange user ID that matches nothing.
Extra layers that help
- Give the app's database user only the permissions it needs.
- Validate input (an ID should be a number).
- Don't show raw database errors to users.
Filtering out quotes is not a fix on its own. Attackers have many ways around it. Parameterised queries are the fix.