Skip to main content
SQL Injection Fundamentals
Lesson 1 of 26

SQL Injection Fundamentals

Learn how untrusted input breaks out of a SQL query, how to recognise and safely demonstrate the flaw in a lab, and how parameterized queries remove it for good.

Intermediate 30 min Pentesting
Authorised environments only — The techniques described here are used only in training labs and on systems you own or have written permission to test.

Learning objectives

  • Explain why concatenating user input into SQL changes the meaning of a query
  • Recognise error-based, UNION-based and boolean-based injection points in a controlled lab
  • Demonstrate an authentication bypass and a data-extraction proof of concept without damaging data
  • Fix a vulnerable query with parameterized statements and apply defence in depth

Recommended first: HTTP Request/Response, Cookies & Session Management

#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:

php
$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:

sql
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:

sql
SELECT id, role FROM users WHERE username = 'admin'-- ' AND password = 'x'
Authentication bypass through string concatenationAuthentication bypass through string concatenationBrowserAppDatabasePOST user=admin'-- &pass=xSELECT ... WHERE username = 'admin'-- ' AND ...1 row (admin)302 Location /dashboard (logged in as admin)The password condition was commented out

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:

  1. 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.
  2. Test logic. Compare id=5 AND 1=1 (stays normal) with id=5 AND 1=2 (changes). Two different responses indicate boolean-based behaviour.
  3. Count columns. For UNION attacks, increase ORDER BY n until an error appears; the last working n is the column count.
  4. Extract carefully. Use UNION SELECT with matching column count and types to read a small amount of data that proves the issue.
Probing a lab target (authorised practice range only)
$ 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.

php
$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 BY or LIMIT input.
  • 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.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge