Building tables and changing data · Lesson 16 of 20
SQL injection: the most dangerous mistake
How user-typed text can hijack your query, and the one right fix.
8 minutes2 games
When code builds a query by gluing in text from the user, the user can type SQL instead of data. That's SQL injection, one of the most dangerous and common vulnerabilities in the web's history.
JavaScript
// ❌ Never do this const name = req.query.name const sql = "SELECT * FROM students WHERE name = '" + name + "'" await db.query(sql)
If the user types a normal name like Omar, fine. But if they type ' OR '1'='1, this is the query that runs. Run it and see:
SQL
-- What the server built from the input ' OR '1'='1 SELECT * FROM students WHERE name = '' OR '1'='1';
The condition is now true for every row, so every student came back. Other inputs can drop tables, skip a login check, or leak password hashes.
JavaScript
// ✅ Parameterized query: the value travels separately from the SQL
await db.query("SELECT * FROM students WHERE name = $1", [name])
// ✅ Query builders and clients do this for you
const { data } = await supabase.from("students").select("*").eq("name", name)Spot the bug
Which line has the vulnerability?
Quick question
Which approach actually prevents SQL injection?
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.