SQL Injection (SQLi) occurs when untrusted user input is directly concatenated into database queries without validation. This allows attackers to manipulate commands and read private tables.
1. How SQL Injection Works
Consider a vulnerable login query:
SELECT * FROM users WHERE username = 'USER_INPUT' AND password = 'PASSWORD'
If an attacker inputs admin' OR '1'='1, the resulting SQL command becomes:
SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = ''
Because '1'='1' is always true, the database bypasses credentials checks and logs the attacker into the admin account.
2. Mitigation: Parameterized Queries
The only secure way to prevent SQL Injection is by using Prepared Statements (parameterized queries). The query structure is compiled first, and parameters are treated strictly as data, never executable code.
Secure PHP PDO Example:
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :user');
$stmt->execute(['user' => $userInput]);
$user = $stmt->fetch();