#Why this matters
SQL injection (SQLi) has sat near the top of web-application risk lists for two decades because it turns a small coding shortcut into full read access to a database, and sometimes much more. In OWASP's Top 10 it is part of the Injection category. The root cause is always the same: the application builds a query by gluing text together, so data supplied by a user is interpreted as SQL code.
#How a query goes wrong
Consider a login form. The server builds this query:
$sql = "SELECT id, role FROM users WHERE username = '" . $_POST['user'] . "' AND password = '" . $_POST['pass'] . "'";When a normal user types alice and s3cret, the database receives:
SELECT id, role FROM users WHERE username = 'alice' AND password = 's3cret'Now the attacker types admin'-- as the username and anything as the password. The quote closes the string early and -- starts a comment, so the password check disappears:
SELECT id, role FROM users WHERE username = 'admin'-- ' AND password = 'x'The database never saw a mistake. It executed exactly the text it was given.
#Finding an injection point
A tester works in small, safe steps and watches how the response changes:
- Break the syntax. Send a single quote
'or a closing parenthesis. A database error, a 500 status, or a blank page suggests the input reaches a query. - Test logic. Compare
id=5 AND 1=1(stays normal) withid=5 AND 1=2(changes). Two different responses indicate boolean-based behaviour. - Count columns. For UNION attacks, increase
ORDER BY nuntil an error appears; the last workingnis the column count. - Extract carefully. Use
UNION SELECTwith matching column count and types to read a small amount of data that proves the issue.
$ curl -s "http://lab.local/item.php?id=5'" | head -n 3
You have an error in your SQL syntax; check the manual for the right syntax near ''' at line 1
$ curl -s "http://lab.local/item.php?id=5%20ORDER%20BY%203--%20" | head -n 3
Item 5: Wireless keyboard
$ curl -s "http://lab.local/item.php?id=5%20ORDER%20BY%204--%20" | head -n 3
Unknown column '4' in 'order clause'The error for ORDER BY 4 tells us the query selects 3 columns. A proof-of-concept UNION SELECT then needs exactly three values.
#Other flavours you will meet
| Type | What you see | Typical signal |
|---|---|---|
| Error-based | Database error text in the page | Verbose errors left enabled |
| UNION-based | Extra rows mixed into normal output | Query results are reflected |
| Boolean blind | Page differs between true and false | Same page, small content change |
| Time-based blind | Response delay | SLEEP(5) style functions |
| Second-order | Payload stored now, executed later | Input saved to a profile, used in an admin report |
#Fixing it properly
The reliable defence is the parameterized (prepared) statement: the SQL text is sent first with placeholders, and values follow separately, so they can never become code.
$stmt = $pdo->prepare('SELECT id, role FROM users WHERE username = :u');
$stmt->execute([':u' => $_POST['user']]);
$user = $stmt->fetch();
if ($user && password_verify($_POST['pass'], $user['password_hash'])) { /* ok */ }Defence in depth adds more layers, but none replaces parameters:
- Allow-list validation for values with a fixed set (sort column, table name), because placeholders cannot bind identifiers.
- Least privilege: the app account should not own the schema, read other applications' databases, or write files.
- Generic error pages and server-side logging so attackers get no schema hints.
- Web application firewalls can reduce noise but are bypassable; treat them as a speed bump.
#Common mistakes
- Escaping quotes by hand or relying on
addslashes: encoding-specific bypasses exist. - Using parameters for values but concatenating
ORDER BYorLIMITinput. - Fixing one endpoint and forgetting similar queries elsewhere (search the codebase for string-built SQL).
- Hiding errors but leaving blind injection intact.
#Summary
SQL injection happens when user input is concatenated into a query so that data becomes code. Detect it by breaking syntax, comparing true/false responses and counting columns; demonstrate impact with minimal, read-only proof. Prevent it with parameterized statements, allow-lists for identifiers, least-privilege database accounts and safe error handling.