SQL Injection Tutorial: What, Why & Defenses

SQL Injection (SQLi) happens when untrusted input is concatenated into a SQL query, allowing attackers to change its meaning.

~6 min read

How the Bug Appears

Vulnerable Pattern (string concatenation)

// ❌ Do not do this (example)
const user = form.username; 
const pass = form.password;

// Concatenating user input into the query:
const sql = "SELECT id FROM users WHERE username='" + user + "' AND password='" + pass + "';";

Because string concatenation is used, special characters inside user/pass can break out of the intended query.

Typical Bypass Payload

' OR '1'='1

The core tautology is OR 1=1 which always evaluates to true, effectively bypassing checks.

The Right Fix

Parameterized Queries (Prepared Statements)

// ✅ Use placeholders and parameters
const sql = "SELECT id FROM users WHERE username = ? AND password = ?";
db.query(sql, [user, pass]);  // driver safely binds values

Parameterized queries (prepared statements) keep data separate from code and prevent SQLi.

Ready to try a safe demo? Open the SQL Injection Challenge