SQL Injection Protection Setup for Websites
SQL injection — attack where attacker injects arbitrary SQL code into application queries. Result: entire database leak, authentication bypass, data modification or deletion. By OWASP statistics, consistently ranks in top three most critical web vulnerabilities.
Root Cause of Vulnerability
Direct concatenation of user input into SQL:
// VULNERABLE
$query = "SELECT * FROM users WHERE email = '" . $_POST['email'] . "'";
// Attacker input: ' OR '1'='1
// Result: SELECT * FROM users WHERE email = '' OR '1'='1'
// Returns all users
Prepared Statements (Parameterized Queries)
Only reliable method — parameterized queries. Values never interpolated into SQL string:
PDO (PHP):
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND active = ?');
$stmt->execute([$email, 1]);
$user = $stmt->fetch();
Eloquent ORM (Laravel):
// All ORM methods use prepared statements automatically
$user = User::where('email', $email)->where('active', true)->first();
// If raw SQL needed — bindParam mandatory
$users = DB::select('SELECT * FROM users WHERE email = ?', [$email]);
Sequelize (Node.js):
const user = await User.findOne({ where: { email, active: true } });
// Raw query
const [results] = await sequelize.query(
'SELECT * FROM users WHERE email = :email',
{ replacements: { email }, type: QueryTypes.SELECT }
);
ORM — Not Safety Guarantee
Some ORM methods accept raw fragments and are vulnerable:
// Laravel — DANGEROUS
User::whereRaw("name = '$name'")->get();
User::orderBy($request->get('sort'))->get(); // vulnerable to ORDER BY injection
// SAFE
User::whereRaw('name = ?', [$name])->get();
$allowedSorts = ['name', 'email', 'created_at'];
$sort = in_array($request->sort, $allowedSorts) ? $request->sort : 'name';
User::orderBy($sort)->get();
Validation and Whitelist for Dynamic Parts
Request parameters that cannot be parameterized (table names, column names, sort direction) checked against whitelist:
$allowedColumns = ['title', 'created_at', 'views'];
$allowedDirections = ['asc', 'desc'];
$column = in_array($request->column, $allowedColumns)
? $request->column
: throw new InvalidArgumentException('Invalid column');
$direction = in_array($request->direction, $allowedDirections)
? $request->direction
: 'asc';
Principle of Least Privilege
Database user running application should have only necessary rights:
-- Create user with only needed rights
CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'strong_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON myapp.* TO 'app_user'@'localhost';
-- Without DROP, CREATE, ALTER, GRANT
Even with successful injection, attacker cannot drop tables or create new ones.
WAF as Additional Layer
Web Application Firewall (ModSecurity, Cloudflare WAF) intercepts typical SQL injections at HTTP level before reaching application. Not replacement for prepared statements — additional barrier.
Vulnerability Scanning
# sqlmap — automatic SQL injection search
sqlmap -u "https://example.com/search?q=test" --dbs --batch
# For POST requests
sqlmap -u "https://example.com/login" --data="email=test&password=test" --dbs
Run only on own systems or with written permission.
Stored Procedures
Stored procedures don't give automatic protection if they concatenate strings:
-- VULNERABLE
CREATE PROCEDURE GetUser(IN userInput VARCHAR(255))
BEGIN
SET @sql = CONCAT('SELECT * FROM users WHERE name = ''', userInput, '''');
PREPARE stmt FROM @sql;
EXECUTE stmt;
END;
-- SAFE — use parameterized queries inside procedures
Code Audit
When working with legacy project, look for patterns:
# Find potentially dangerous constructs in PHP
grep -rn 'query.*\$_\(GET\|POST\|REQUEST\)' src/
grep -rn 'whereRaw.*\.' app/
grep -rn '"SELECT.*".*\.' src/
Implementation Timeline
- Audit existing code: 1–3 days depending on scope
- Fix vulnerable queries: 2–7 days
- WAF + monitoring setup: 1 day







