Why prepared statements stop SQL injection

Beginner  Oct 30, 2026

See the problem with building SQL from user input, and the one-line fix.

Why prepared statements stop SQL injection
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

The problem

Never put user input straight into SQL:

// DANGEROUS
$sql = "SELECT * FROM users WHERE email = '" . $_GET['email'] . "'";

If someone sends ' OR '1'='1, the query changes meaning and may return every user.

How the code in this section fits into the page.
How the code in this section fits into the page.

The fix: prepared statements

Send the SQL and the data separately. The database treats the data as plain values, never as code.

$st = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$st->execute([$_GET['email']]);
$user = $st->fetch();
The fix: prepared statements
The fix: prepared statements

Named placeholders

$st = $pdo->prepare('SELECT * FROM posts WHERE category = :cat AND published = :p');
$st->execute([':cat' => $cat, ':p' => 1]);

Remember

  • Table and column names cannot be placeholders. Check them against a fixed list.
  • Prepared statements stop SQL injection, but you still need to escape output (XSS) and check permissions.

More tutorials