Prevent SQL injection
How SQL injection works and how to write queries that are not vulnerable to it.
SQL injection is one of the most dangerous security vulnerabilities. Learn how to protect your applications.
The Problem
-- DANGEROUS: String concatenation const query = "SELECT * FROM users WHERE name = '" + userInput + "'"; -- If userInput is: ' OR '1'='1 -- Query becomes: SELECT * FROM users WHERE name = '' OR '1'='1' -- This returns ALL users! -- Even worse: '; DROP TABLE users; -- -- This deletes the entire table!
The Solution: Parameterized Queries
-- JavaScript/Node.js with better-sqlite3
const stmt = db.prepare('SELECT * FROM users WHERE name = ?');
const user = stmt.get(userInput);
-- Python with sqlite3
cursor.execute('SELECT * FROM users WHERE name = ?', (user_input,))
-- The database handles escaping safelyRules
X
NEVER concatenate user input into SQL strings
ALWAYS use parameterized queries / prepared statements
ALWAYS use an ORM that handles parameterization
ALWAYS validate and sanitize input on top of parameterization