← Back to Error Lab

Security Flaw: SQL Injection via unsanitized user input

Published 2026-04-09

Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.

Root Cause

SQL Injection (SQLi) is a critical security vulnerability that occurs when an application constructs a database query dynamically by concatenating raw, untrusted user input directly into the SQL string. Attackers can exploit this by inputting crafted strings containing SQL syntax (like `' OR 1=1 --`), which alter the intended logic of the query. This can lead to unauthorized data access, modification, or even complete deletion of tables. Despite being one of the oldest and most well-understood web vulnerabilities, it remains prevalent because developers often take shortcuts instead of using parameterized queries. Any input that originates outside the application (forms, API parameters, headers) must be treated as malicious.

Fix / Solution

Never construct SQL queries using string concatenation or template literals with user input. Always use parameterized queries (also known as prepared statements) provided by your database driver or ORM. Parameterized queries send the SQL command and the data separately, ensuring the database engine treats the input strictly as data, not as executable code.

Code Snippet

// ❌ Broken (Vulnerable to SQL Injection)
const username = req.body.username;
// If username is "admin' --", the query becomes: SELECT * FROM users WHERE username = 'admin' --'
const query = `SELECT * FROM users WHERE username = '${username}'`;
db.execute(query);

// ✅ Fixed (Safe Parameterized Query)
const username = req.body.username;
const query = 'SELECT * FROM users WHERE username = ?';
db.execute(query, [username]);