Skip to content
DevPlainly
Security

SQL Injection Explained: How It Works and How to Stop It

What SQL injection is, shown on a real database, and how to prevent it with parameterized queries in Python, Node.js and PHP, tested on PostgreSQL.

Published
Reading time
7 min read
Contents
  1. What SQL injection is
  2. See it happen
  3. What an attacker can do with it
  4. The fix: parameterized queries
  5. Python (psycopg)
  6. Node.js (pg)
  7. PHP (PDO)
  8. Why escaping and validation aren't the fix
  9. When you can't use a placeholder
  10. Extra layers that limit the damage
  11. How to check your own code
  12. FAQ
  13. Is SQL injection still a problem today?
  14. Do ORMs protect against SQL injection?
  15. Are NoSQL databases safe from injection?
  16. Is it legal to test for SQL injection?
  17. Further reading

SQL injection is one of the oldest security bugs in web development, and it still shows up in real applications, student projects and production code alike. The good news: it's also one of the easiest to prevent completely, once you understand what goes wrong.

This guide shows SQL injection happening on a real database we control, explains why it works, and fixes it in Python, Node.js and PHP. Every query and output below was run on PostgreSQL.

Nil's note

We learned prepared statements in class, and I'm really glad we did: since then I've used them in every form I've built, especially in the websites we make at school, just in case. It costs nothing once it's a habit, and this guide shows exactly what it protects you from.

What SQL injection is

SQL injection happens when text that a user types ends up as part of the SQL code your app sends to the database. The database can't tell which part you wrote and which part came from the user, so the user's text can change what the query does.

It always starts the same way: building a query by gluing strings together.

query = f"SELECT id, username, email FROM users WHERE username = '{username}'"

If username is ana, everything is fine. If it contains a quote, the user is no longer typing a value: they're writing SQL.

See it happen

We set up a test database with three users and a small Python function that looks a user up by name, the way a profile page or an admin search might:

import psycopg

conn = psycopg.connect("postgresql://webapp:demo-only@localhost/shop")

def find_user_unsafe(username):
    # DON'T: the input becomes part of the SQL
    query = f"SELECT id, username, email FROM users WHERE username = '{username}'"
    return conn.execute(query).fetchall()

A normal search works as expected:

input: 'ana'
  SQL sent: SELECT id, username, email FROM users WHERE username = 'ana'
  result:   [(1, 'ana', 'ana@example.com')]

Now the same function with the input ' OR '1'='1:

input: "' OR '1'='1"
  SQL sent: SELECT id, username, email FROM users WHERE username = '' OR '1'='1'
  result:   [(1, 'ana', 'ana@example.com'), (2, 'ben', 'ben@example.com'), (3, 'carla', 'carla@example.com')]

The first quote closed the string early, and OR '1'='1' added a condition that's always true. The query now matches every row, and the page leaks every user's email address.

What an attacker can do with it

Depending on the query and the database permissions, SQL injection can let someone:

  • Read data they shouldn't, like other users' emails, as above, or data from other tables.
  • Log in as someone else, when a login form checks the password with a query built from strings.
  • Change or delete data, if the app's database user is allowed to.

That's why it has been in the OWASP Top 10, the best-known list of web security risks, for as long as the list has existed. The fix is the same in every case.

The fix: parameterized queries

A parameterized query (also called a prepared statement) sends the SQL and the values separately. The SQL has a placeholder where the value goes, and the database always treats what fills it as data, never as code. A quote in the input is just a character in a username.

Python (psycopg)

def find_user_safe(username):
    # DO: the SQL and the value travel separately
    return conn.execute(
        "SELECT id, username, email FROM users WHERE username = %s", (username,)
    ).fetchall()
input: "' OR '1'='1"
  result: []

No user is called ' OR '1'='1, so the result is empty. With SQLite's built-in sqlite3 module the placeholder is ? instead of %s.

Node.js (pg)

async function findUser(username) {
  const { rows } = await client.query("SELECT id, username, email FROM users WHERE username = $1", [username]);
  return rows;
}
"ana" -> [{"id":1,"username":"ana","email":"ana@example.com"}]
"' OR '1'='1" -> []

With MySQL's mysql2 package the placeholder is ?.

PHP (PDO)

function findUser(PDO $pdo, string $username): array {
    $stmt = $pdo->prepare("SELECT id, username, email FROM users WHERE username = :username");
    $stmt->execute(["username" => $username]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
"ana" -> [{"id":1,"username":"ana","email":"ana@example.com"}]
"' OR '1'='1" -> []

The same pattern works with MySQL: only the connection string changes.

Why escaping and validation aren't the fix

  • Escaping quotes by hand (replacing ' with '') is easy to get wrong: a missed field, a different encoding or a number field without quotes, and the hole is back. Placeholders make the mistake impossible instead of unlikely.
  • Input validation is good practice. A username that only allows letters and numbers is a reasonable rule. But it's a second layer, not a replacement: one day someone adds a field that allows quotes, like a name ("O'Brien") or a comment, and the query is open again.

When you can't use a placeholder

Placeholders work for values, not for parts of the SQL itself like table names, column names or ASC/DESC. A common case is a "sort by" option in a table. The safe way is an allowlist: only accept names you've written yourself.

SORTABLE = {"username", "email"}

def list_users(sort):
    if sort not in SORTABLE:
        sort = "username"
    return conn.execute(f"SELECT id, username, email FROM users ORDER BY {sort}").fetchall()

The user chooses between options; they never write the SQL.

Extra layers that limit the damage

  • Give the app a database user with only the permissions it needs. Our test app's user can only read the users table. When it tries to delete a row, PostgreSQL refuses: permission denied for table users. If an injection ever slipped through, it couldn't destroy data.
  • Use an ORM or query builder (SQLAlchemy, Prisma, Eloquent, Django's ORM). They use parameters for you. Be careful with their "raw SQL" functions, where you're back to writing queries yourself.
  • Don't show database errors to users. Detailed error messages tell an attacker about your tables and queries. Log them, and show a generic message.
  • Keep the database off the internet. In a Docker Compose setup, a database without published ports is only reachable by your app, and its password belongs in a .env file kept out of Git.

How to check your own code

Search your project for SQL built from strings. These are the patterns to look for:

LanguageRiskySafe
Pythonf"... WHERE id = {id}", "..." + nameexecute("... WHERE id = %s", (id,))
JavaScript`... WHERE id = ${id}`query("... WHERE id = $1", [id])
PHP"... WHERE id = $id", "..." . $nameprepare("... WHERE id = :id") then execute([...])

Then try it yourself, on your own local copy: type ' OR '1'='1 into each search or form field and check that nothing unexpected comes back.

FAQ

Is SQL injection still a problem today?

Yes. Frameworks and ORMs have made it rarer, but it still appears wherever someone writes a query by joining strings: quick scripts, admin panels, old code and student projects. It stays in the OWASP Top 10 for that reason.

Do ORMs protect against SQL injection?

Their normal methods do, because they use parameters for you. Raw query functions don't, if you build the SQL string yourself and pass it in. Use their placeholder syntax there too.

Are NoSQL databases safe from injection?

Not automatically. MongoDB, for example, has its own injection problems when user input is turned into query operators. The same rule applies: never let user input become part of the query's structure.

On your own code and your own databases, yes. On websites or systems you don't own, only with the owner's written permission; testing without it is illegal in most countries.

Further reading

Written by Nil Martinez

Developer · DAM & DAW student

Developer studying multiplatform (DAM) and web (DAW) application development. I work every day with TypeScript, Angular, React, Java, Python, FastAPI, MySQL and Docker on Kubuntu, and I write about the tools I actually use.

How I test and write each guideGitHub

Keep reading