SQL Injection: Short Questions, Plain Answers

SQL injection sounds technical, but the idea is simple and so is the main fix. These short answers are written for people building their first database-backed app.

Understanding it

What is SQL injection, in one sentence?

It is when text typed by a user ends up being run as part of your SQL command, instead of being treated only as data.

How does that happen?

When code builds a query by gluing strings together, for example "... WHERE name = '" + name + "'". A value containing a quote can close your string early and add its own SQL after it.

What can an attacker do with it?

Depending on the app and the database account, they might read data they should not see, log in as someone else, change records or delete them. It is one of the best-known web security problems for exactly that reason.

Preventing it

What is the main fix?

Placeholders, also called parameters or bind variables. You write WHERE name = ? and pass the value separately. The database always treats it as a value.

Do all languages support placeholders?

Yes, every mainstream database library does. The symbol differs: ? (SQLite, many MySQL drivers, JDBC), $1 (Node.js pg), %s (Python's psycopg and mysqlclient), or named ones like :name.

Is escaping quotes myself just as good?

No. Hand-written escaping is easy to get wrong in small ways. Placeholders are simpler and reliable.

Does an ORM protect me?

Its normal query methods use placeholders for you. Be careful with "raw SQL" features where you write SQL strings yourself; use placeholders there too.

Can I use a placeholder for a column or table name?

No, only for values. If users choose a sort column, compare their choice to a fixed list of allowed names in your code and use only names from that list.

Extra protection

What else helps?

Should I check user input as well?

Yes, for correctness and as an extra layer: an age should be a number, an email should look like an email. But input checks are not a replacement for placeholders.

Testing

How do I check my own code?

Search your code for SQL built with +, string formatting or template strings that include user input. Each one should become a placeholder. Then try a value containing a single quote, such as O'Brien, in your forms: with placeholders it works normally.

Can I test other people's websites?

No. Only test systems you own or have written permission to test.

Where can I practise safely?

Our hands-on exercise breaking and fixing a tiny login form runs entirely on your own computer.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

This is a static page of sample discussion topics. There is no live forum, membership or user community on this site.