SQL Injection — Explained with Examples
SQL injection is a code injection technique that exploits vulnerable SQL queries by inserting malicious SQL statements into user input fields.
SQL Injection (SQLi) is one of the oldest and most dangerous web vulnerabilities. It occurs when user input is concatenated directly into SQL queries without proper sanitization or parameterization.
How SQL Injection Works
Consider a login form that builds a query like this:
// VULNERABLE — never do this
const query = `SELECT * FROM users WHERE email = '${email}' AND password = '${password}'`;If an attacker enters:
- Email:
admin@example.com' -- - Password:
anything
The query becomes:
SELECT * FROM users WHERE email = 'admin@example.com' --' AND password = 'anything'The -- comments out the password check. The attacker logs in as admin without knowing the password.
Types of SQL Injection
In-band (Error-based) — attacker sees database error messages with useful information.
In-band (Union-based) — attacker uses UNION SELECT to extract data from other tables.
' UNION SELECT username, password FROM admins --Blind (Boolean-based) — attacker infers information from true/false responses.
' OR (SELECT SUBSTRING(password,1,1) FROM admins WHERE id=1) = 'a' --If the page loads normally, the first character of the admin password is ‘a’.
Prevention: Parameterized Queries
// SECURE — use parameterized queries
const query = 'SELECT * FROM users WHERE email = ? AND password = ?';
db.query(query, [email, password], (err, results) => {
// SQL injection is impossible here
});
// ORM example (Sequelize)
const user = await User.findOne({
where: { email: email, password: password }
});# Python (parameterized with SQLAlchemy)
user = session.query(User).filter(
User.email == email,
User.password == password
).first()Real-World Analogy
SQL injection is like a bank teller who reads your deposit slip literally. If you write “Deposit $1000 and also give me all cash from the vault,” the teller follows both instructions. A parameterized query is a teller with a strict form that only accepts a number in the “amount” field — any extra text is treated as invalid, not as additional instructions.
Related Terms
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro