Skip to content
Optimal Lab

Security · interactive

SQL injection

A login form looks up the username you type. If the code pastes your text straight into the SQL, a quote mark ends the string early and the rest of your input becomes part of the query. The database here is a simulation.

Username typed

' OR '1'='1

SQL sent to the database

SELECT * FROM users WHERE username = '' OR '1'='1'

Rows returned

1adminadmin
2aliceuser
3bobuser

'1'='1' is always true, so every row matches. The app logs in as the first one: admin.

'1'='1' is always true, so every row matches. The app logs in as the first one: admin.

Username

How the code builds the query

Step 1 of 4

  1. 1

    Gluing text into SQL

    `... WHERE username = '${input}'` works for alice. The input is trusted to be just a name.

    "SELECT … WHERE username = '" + input + "'"

  2. 2

    Input becomes code

    A ' closes the string. What follows is parsed as SQL: OR conditions, comments, even new statements.

    The attacker is now writing part of your query.

  3. 3

    Parameterized queries

    Send the SQL with a placeholder, and the value separately. The database never parses the value as SQL, whatever it contains.

    db.query("… WHERE username = $1", [input])

  4. 4

    And limit the damage

    Use ORMs and query builders that parameterize for you, and connect with a database user that can't DROP tables.

    Escaping by hand is easy to get wrong; parameters aren't.

In production

Tools and technologies

Parameterized queries are built into every major driver and ORM.

Not tied to one language — use these names when you search docs or design a system.