Introduction to SQL Injection
Understand the mechanics of one of the most critical web vulnerabilities and learn how poorly sanitized inputs can compromise entire databases.
The Anatomy of a Flaw
SQL Injection (SQLi) occurs when an application improperly handles user-supplied data before sending it to a backend database. Instead of treating the input as pure data, the database interprets it as executable code.
Critical Concept
The core issue is a failure to separate Data from Context. When the interpreter cannot distinguish between the query structure and the user's input, arbitrary commands can be executed.
A Vulnerable Query
Consider a simple authentication mechanism. The backend code might construct a query like this:
$username = $_POST['user'];
$password = $_POST['pass'];
// VULNERABLE CODE - Direct concatenation
$query = "SELECT * FROM users WHERE username = '" . $username . ";
If an attacker submits admin' -- as the username, the constructed query becomes:
SELECT * FROM users WHERE username = 'admin' --'
The -- sequence comments out the rest of the query (e.g., password checking), bypassing authentication entirely.