SQL injection and parameterized queries

Introduction

A login form asks for a user name and a PIN, and the code builds a database query from them. If the code simply pastes what the user typed into the query, a user can type SQL instead of a name and change what the query means. That is SQL injection, one of the oldest web attacks and still one of the most damaging: one input box can read, change or delete an entire database.

Everything in this lesson runs against a fake, three-row table inside this page. Never try these inputs on a system you do not own or have written permission to test.

How it works

The vulnerable pattern is string concatenation:

sql = "SELECT * FROM users WHERE name = '" + name + "' AND pin = '" + pin + "'"

The programmer meant name to be data. But the database receives one string and reads all of it as SQL. If the name contains a quote, it ends the string early, and whatever follows becomes part of the command:

  • ' OR '1'='1' -- turns the condition into name = '' OR '1'='1', which is true for every row, and -- starts a comment, so the PIN check disappears.
  • admin' -- logs in as admin without any PIN.
  • A single stray quote often causes a database error, and detailed error messages tell an attacker how the query is built.

The fix is a parameterized query (also called a prepared statement). The SQL is written once with placeholders, WHERE name = ? AND pin = ?, and the values are sent separately. The database parses the SQL before it sees the values, so a value can never become code, whatever characters it contains. Try both side by side:

Press ' OR '1'='1' --: the vulnerable query logs in every account, while the parameterized query compares the whole text as a name, finds no such user and refuses.

Example

The program prints what string concatenation sends to the database for honest input and for two attacks, then what a parameterized query sends.

// What string concatenation sends to the database, for honest input and for an attack.
function unsafeQuery(name, pin) {
  return "SELECT * FROM users WHERE name = '" + name + "' AND pin = '" + pin + "'";
}

console.log(unsafeQuery("rahim", "4821"));
console.log(unsafeQuery("' OR '1'='1' --", "anything"));
console.log(unsafeQuery("admin' --", ""));

// A parameterized query keeps the SQL fixed; the values travel separately and are never read as SQL.
const sql = "SELECT * FROM users WHERE name = ? AND pin = ?";
const values = ["' OR '1'='1' --", "anything"];
console.log(sql + "   values: " + JSON.stringify(values));
Open in compiler

Line by line

  1. unsafeQuery glues the inputs into the SQL text with +.
  2. For rahim and 4821 the result is the intended query.
  3. For ' OR '1'='1' -- the first quote closes the name string, OR '1'='1' adds a condition that is always true, and -- comments out the rest, including the PIN check.
  4. For admin' -- the name is admin and the PIN check is commented out.
  5. With a parameterized query, the SQL stays exactly the same for every input; the attack text travels only as a value in the list.

Expected result

SELECT * FROM users WHERE name = 'rahim' AND pin = '4821'
SELECT * FROM users WHERE name = '' OR '1'='1' --' AND pin = 'anything'
SELECT * FROM users WHERE name = 'admin' --' AND pin = ''
SELECT * FROM users WHERE name = ? AND pin = ?   values: ["' OR '1'='1' --","anything"]

In the real world

  • Every mainstream database library supports parameters: ? or $1 placeholders in Node.js drivers, cursor.execute(sql, params) in Python, PreparedStatement in Java.
  • ORMs (libraries that build SQL for you) use parameters by default, but most also offer a "raw SQL" escape hatch where the same mistake is possible.
  • Injection is not only SQL: the same idea breaks shell commands, LDAP queries and template engines whenever input is pasted into code.
  • Databases' own error messages should never reach the browser; show a generic message and log the details on the server.

Common mistakes

  • Escaping quotes by hand instead of using parameters; it is easy to miss a case, such as a different quote character or an encoding trick.
  • Parameterizing values but pasting column or table names, for example a sort column chosen by the user. Use an allow-list for those.
  • Trusting input because it came from your own front end. Attackers send requests directly.
  • Giving the app's database account full rights. If injection happens anyway, least privilege limits the damage.

Best practices

  • Use parameterized queries for every value, every time.
  • Check input against what you expect (a PIN is 4 digits) as an extra layer, not the main defence.
  • Give the application's database user only the rights it needs, so it cannot drop tables.
  • Show generic error messages to users and log details privately.

Summary

SQL injection happens when user input is pasted into SQL text, so a quote in the input ends the data and the rest runs as SQL. Classic payloads make conditions always true or comment out checks. A parameterized query sends the SQL and the values separately, so input can never become code; it is the fix, and input checks and least privilege are extra layers.

Quick check

1. Why does ' OR '1'='1' -- bypass a login built with string concatenation?
2. What makes a parameterized query safe?
3. A sort feature takes ?sort=price and pastes it as a column name into ORDER BY. What is the safe fix?
4. Injection got through anyway. Which extra layer limits the damage?

Key takeaways

  • Never paste input into SQL; use parameters for every value.
  • Quotes in input end strings early, and -- comments out the rest.
  • Column and table names need an allow-list, because placeholders cannot hold them.
  • Least privilege and generic errors limit the damage if a mistake slips through.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.