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. SQLi Types
- Union-Based SQLi: Uses the UNION operator to combine query results with database tables, displaying private data directly on screen.
- Blind SQLi: The page doesn’t print error data, but query changes modify server responses (Boolean-based or Time-based delay).
3. 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();
Auditing Tip: Regularly review source code dependencies and use automated scanners like sqlmap in local sandboxes to audit entry parameters.