TExcelTAD
Home › PHP › PHP Prepared Statements

PHP Prepared Statements

The most dangerous mistake in database code is gluing user input directly into an SQL string. A prepared statement fixes this: you send the SQL with placeholders first, and the values travel separately. The database never confuses data with code.

The problem: SQL injection

Imagine a login form that builds its query like this:

php
<?php
$name = $_POST['name'];
$sql  = "SELECT * FROM users WHERE name = '$name'";

If someone types x' OR '1'='1 as their name, the query becomes ... WHERE name = 'x' OR '1'='1', which matches every user. Let's watch that happen on a harmless in-memory table:

php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE TABLE users (name TEXT, role TEXT)");
$pdo->exec("INSERT INTO users VALUES ('lena', 'admin'), ('omar', 'editor'), ('pia', 'viewer')");

$input = "x' OR '1'='1";   // pretend this came from a form

// UNSAFE: the input becomes part of the SQL code
$sql = "SELECT name FROM users WHERE name = '$input'";
echo "SQL sent: $sql\n";
$rows = $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN);
echo "Unsafe query found: ", implode(', ', $rows), "\n";

// SAFE: the input is only ever treated as a value
$stmt = $pdo->prepare('SELECT name FROM users WHERE name = ?');
$stmt->execute([$input]);
$rows = $stmt->fetchAll(PDO::FETCH_COLUMN);
echo "Safe query found: ", count($rows), " rows\n";
SQL sent: SELECT name FROM users WHERE name = 'x' OR '1'='1'
Unsafe query found: lena, omar, pia
Safe query found: 0 rows

Note: Escaping quotes by hand or with addslashes() is not a fix. Use prepared statements for every query that contains a value you didn't write yourself.

Three steps: prepare, execute, fetch

  1. prepare($sql) — send SQL that contains placeholders and get a PDOStatement.
  2. execute($values) — supply the values and run it.
  3. fetch() / fetchAll() — read the results (for SELECT).

Positional and named placeholders

Style SQL execute() argument
Positional WHERE price < ? AND stock > ? [20, 0] (in order)
Named WHERE price < :max AND stock > :min ['max' => 20, 'min' => 0]

Named placeholders are easier to read when a query has many values. You can't mix both styles in one statement.

php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:', options: [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE products (name TEXT, price REAL, stock INTEGER)');
$pdo->exec("INSERT INTO products VALUES
    ('Green tea', 6.5, 40), ('Matcha', 18.0, 0), ('Oolong', 12.25, 7), ('Chai', 9.0, 15)");

// Positional placeholders
$stmt = $pdo->prepare('SELECT name, price FROM products WHERE price < ? AND stock > ? ORDER BY price');
$stmt->execute([15, 0]);
foreach ($stmt as $p) {
    echo "{$p['name']}: {$p['price']}\n";
}

// Named placeholders
$stmt = $pdo->prepare('SELECT COUNT(*) FROM products WHERE stock BETWEEN :low AND :high');
$stmt->execute(['low' => 1, 'high' => 20]);
echo "Low-stock products: ", $stmt->fetchColumn(), "\n";
Green tea: 6.5
Chai: 9
Oolong: 12.25
Low-stock products: 2

Reusing a statement

A prepared statement can be executed many times with different values. The database parses the SQL once, which is both safe and fast for bulk inserts.

php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE scores (player TEXT, points INTEGER)');

$insert = $pdo->prepare('INSERT INTO scores (player, points) VALUES (:player, :points)');

$results = [['Kai', 120], ["O'Neil", 95], ['Rosa', 140]];
foreach ($results as [$player, $points]) {
    $insert->execute(['player' => $player, 'points' => $points]);
}
echo "Inserted ", count($results), " rows\n";

$best = $pdo->prepare('SELECT player, points FROM scores WHERE points >= ? ORDER BY points DESC');
foreach ([100, 130] as $limit) {
    $best->execute([$limit]);
    $names = array_map(fn($r) => "$r[0] ($r[1])", $best->fetchAll(PDO::FETCH_NUM));
    echo "At least $limit: ", implode(', ', $names), "\n";
}
Inserted 3 rows
At least 100: Rosa (140), Kai (120)
At least 130: Rosa (140)

The apostrophe in O'Neil caused no trouble at all — the value never becomes part of the SQL text.

bindValue() and types

Instead of passing an array to execute(), you can bind each value with an explicit type. This is useful for LIMIT/OFFSET, which must be integers, and for NULL values.

php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT, tag TEXT)');
$ins = $pdo->prepare('INSERT INTO notes (body, tag) VALUES (?, ?)');
foreach (['buy milk', 'call mum', 'fix bike', 'read book', 'water plants'] as $i => $body) {
    $ins->bindValue(1, $body, PDO::PARAM_STR);
    $ins->bindValue(2, $i % 2 ? null : 'home', $i % 2 ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $ins->execute();
}

$page = $pdo->prepare('SELECT id, body, tag FROM notes ORDER BY id LIMIT :limit OFFSET :offset');
$page->bindValue(':limit', 2, PDO::PARAM_INT);
$page->bindValue(':offset', 2, PDO::PARAM_INT);
$page->execute();
foreach ($page->fetchAll(PDO::FETCH_ASSOC) as $n) {
    echo "#{$n['id']} {$n['body']} [", $n['tag'] ?? 'no tag', "]\n";
}
#3 fix bike [home]
#4 read book [no tag]
Constant Use for
PDO::PARAM_STR text (the default)
PDO::PARAM_INT integers, LIMIT, OFFSET
PDO::PARAM_BOOL booleans
PDO::PARAM_NULL SQL NULL

Tip: Placeholders can only stand for values. Table names, column names and ASC/DESC cannot be bound — if they come from the user, check them against an allow-list such as in_array($col, ['name', 'price'], true).

Test yourself

Why do prepared statements prevent SQL injection?

  1. They escape quotes with addslashes()
  2. Values are sent separately and never parsed as SQL
  3. They only allow SELECT statements
  4. They encrypt the query

Which execute() call matches WHERE city = :city?

  1. execute(['city' => 'Oslo'])
  2. execute('Oslo')
  3. execute([':city', 'Oslo'])
  4. execute(['Oslo', 'city'])

Which part of a query can NOT be a placeholder?

  1. A value in WHERE
  2. A value in INSERT ... VALUES
  3. A table name
  4. A LIMIT number