Skip to content

Database access with PDO and prepared statements explained

Accessing a database from PHP almost always means PDO. This article explains why prepared statements are the standard, shows with runnable examples what a placeholder prevents, and where its limits lie.

  • Who it is forDevelopers, from beginner to advanced
  • LevelBasics
  • Reading timeabout 10 minutes
  • Last updated24 October 2026

What you will learn

  • How to open a PDO connection with a sensible error mode
  • Why a placeholder prevents SQL injection, demonstrated with the same input value
  • What placeholders cannot replace: column and table names, IN lists
  • How fetch modes, data types and transactions fit together

In short

PDO (PHP Data Objects) is the built-in interface PHP uses to talk to databases: the same functions for MySQL, MariaDB, PostgreSQL or SQLite, each through its own driver. The PHP manual stresses that PDO unifies access, not the database itself: the SQL remains database-specific.

Access is safe when the SQL text is fixed and user input is passed separately as values. That is exactly what a prepared statement does: the database first receives the query with placeholders and then the values. A value can therefore never turn into SQL. The OWASP cheat sheet on SQL injection lists this technique as the primary defence, which is why it is the standard.

Opening a connection and choosing the error mode

A connection consists of a DSN (data source name, such as mysql:host=db;dbname=shop;charset=utf8mb4 or sqlite::memory:), a user name, a password and options. Two options should always be set deliberately:

  • PDO::ATTR_ERRMODE: since PHP 8.0, PDO::ERRMODE_EXCEPTION is the default; before that, PDO reported errors silently through return values only. Set it explicitly anyway, so the intention is visible in the code.
  • PDO::ATTR_DEFAULT_FETCH_MODE: defines the shape in which rows come back, usually PDO::FETCH_ASSOC (column name as key).

If the connection fails, PDO throws a PDOException regardless of the configured error mode. Its message can contain host or database names, so it belongs in the log, not on the screen; how to separate the two is covered in error handling and logging. Credentials live in configuration outside the code, not in the source.

PHP 8.4 also introduced PDO::connect(). Where one exists, it returns a driver-specific subclass such as Pdo\Mysql or Pdo\Sqlite with that driver’s functions. new PDO(…) continues to work.

What a placeholder does

The following script sends the same malicious search term to the database twice: once by string concatenation and once as a placeholder. With concatenation, the input x' OR '1'='1 closes the quotation marks and appends a condition that is always true.

PHPPHP 8.4 · tested with PHP 8.3, 8.4 and 8.5 CLI, SQLite
<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:', options: [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE customer (id INTEGER PRIMARY KEY, email TEXT, credit INTEGER)');
$pdo->exec("INSERT INTO customer (email, credit) VALUES
    ('anna@example.com', 120), ('ben@example.com', 80), ('cem@example.com', 300)");

$input = "x' OR '1'='1";   // what an attacker types into the search field

// Wrong: the input becomes part of the SQL text
$rows = $pdo->query("SELECT email FROM customer WHERE email = '$input'")->fetchAll();
echo 'concatenated: ', count($rows), " rows\n";

// Right: the SQL text is fixed, the input travels separately as a value
$stmt = $pdo->prepare('SELECT email, credit FROM customer WHERE email = :email');
$stmt->execute(['email' => $input]);
echo 'prepared:     ', count($stmt->fetchAll()), " rows\n";

$stmt->execute(['email' => 'cem@example.com']);   // same statement, new value
var_dump($stmt->fetch());
Output: concatenated: 3 rows, prepared: 0 rows, followed by the row for cem@example.com with credit as an integer. With concatenation the query returns every customer; with a placeholder it looks for an email address that literally reads x' OR '1'='1 and finds none.

A few rules from the PHP manual on PDO::prepare():

  • Named placeholders (:email) and question-mark placeholders (?) cannot be mixed in the same statement.
  • Using the same named placeholder twice is only allowed with emulation switched on (more on that below). If in doubt, use two names.
  • A prepared statement can be executed many times with new values, as in the last step of the example.

What placeholders cannot do

The manual is unambiguous: a placeholder represents one complete value. Neither part of a value, nor a keyword, nor an identifier such as a table or column name can be bound, and neither can several values for an IN() list. What happens if you try anyway is instructive:

PHPPHP 8.4 · tested with PHP 8.3, 8.4 and 8.5 CLI, SQLite
<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:', options: [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec('CREATE TABLE customer (id INTEGER PRIMARY KEY, email TEXT, credit INTEGER)');
$pdo->exec("INSERT INTO customer (email, credit) VALUES
    ('anna@example.com', 120), ('ben@example.com', 80), ('cem@example.com', 300)");

// A placeholder is a value, not a column: this sorts by the constant 'credit'
$stmt = $pdo->prepare('SELECT email FROM customer ORDER BY :column DESC');
$stmt->execute(['column' => 'credit']);
echo 'placeholder: ', implode(', ', $stmt->fetchAll(PDO::FETCH_COLUMN)), "\n";

// A placeholder for a table name does not even parse
try {
    $pdo->prepare('SELECT * FROM :table');
} catch (PDOException $e) {
    echo 'table name:  ', $e->getMessage(), "\n";
}

// Identifiers come from an allow-list in the code, never from the request
$sortable = ['credit' => 'credit', 'email' => 'email'];
$requested = 'credit';                       // e.g. $_GET['sort']
$column = $sortable[$requested] ?? 'id';
$sql = "SELECT email FROM customer ORDER BY $column DESC";
echo 'allow-list:  ', implode(', ', $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN)), "\n";
Output: placeholder: anna, ben, cem — insertion order, not sorted by credit; table name: a syntax error; allow-list: cem, anna, ben — correctly sorted.

The first variant is the more dangerous one precisely because it raises no error. The database sorts by the string 'credit', which is identical on every row, and returns the rows in whatever order it likes. In a test with three records, that is easy to miss.

For identifiers, OWASP recommends an allow-list in the code: the value from the request only selects from a fixed set, and anything else falls back to a default. The same goes for sort direction: turn the input into a yes/no and pick ASC or DESC from that. For IN() lists, generate as many placeholders as there are values, as the next example shows.

Fetching results and grouping changes

The third example shows both on a small accounts table: an IN() list with generated placeholders, and a transfer that applies completely or not at all.

PHPPHP 8.4 · tested with PHP 8.3, 8.4 and 8.5 CLI, SQLite
<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:', options: [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec('CREATE TABLE account (id INTEGER PRIMARY KEY, balance INTEGER CHECK (balance >= 0))');
$pdo->exec('INSERT INTO account (id, balance) VALUES (1, 100), (2, 50), (3, 0)');

// IN list: one placeholder per value, generated from the number of values
$ids = [1, 3];
$marks = implode(', ', array_fill(0, count($ids), '?'));
$stmt = $pdo->prepare("SELECT id, balance FROM account WHERE id IN ($marks)");
$stmt->execute($ids);
var_dump($stmt->fetchAll(PDO::FETCH_KEY_PAIR));   // ints, not strings

// Transaction: both bookings or neither
$move = $pdo->prepare('UPDATE account SET balance = balance + :delta WHERE id = :id');
try {
    $pdo->beginTransaction();
    $move->execute(['delta' => 80, 'id' => 2]);     // credit first
    $move->execute(['delta' => -80, 'id' => 1]);    // ok: 100 - 80
    $move->execute(['delta' => -80, 'id' => 1]);    // violates CHECK
    $pdo->commit();
} catch (PDOException $e) {
    $pdo->rollBack();
    echo 'rolled back: ', $e->getCode(), "\n";
}
var_dump($pdo->query('SELECT id, balance FROM account')->fetchAll(PDO::FETCH_KEY_PAIR));
Output: first [1 => 100, 3 => 0] as integers, then rolled back: 23000 and unchanged balances 100, 50, 0. The second debit breaks the CHECK rule, and both changes already executed are undone.

Fetch modes

Frequently used fetch modes of PDOStatement::fetch() and fetchAll()
ModeResultTypical use
PDO::FETCH_ASSOCan array per row, keyed by column namethe normal case
PDO::FETCH_COLUMNonly the first column, as a flat lista list of IDs or names
PDO::FETCH_KEY_PAIRfirst column as key, second as valueselect lists, lookups
PDO::FETCH_CLASSan object of a given class per rowdata objects

Since PHP 8.1, the SQLite and MySQL drivers return integers and floats as PHP numbers rather than strings; the PDO::ATTR_STRINGIFY_FETCHES option restores the old behaviour. Worth knowing if you take over older code that compares against '1' with ===. fetch() returns false when there are no more rows, and fetchAll() loads everything into memory at once, so read large results row by row.

Transactions

By default PDO runs in autocommit mode: every statement takes effect immediately. With beginTransaction(), commit() and rollBack() you group several changes into one operation that applies completely or not at all, the property that PHP in the backend describes as “nothing is half saved”. PDO rolls back an open transaction itself when the script ends. Be careful with MySQL and Oracle: statements such as CREATE TABLE silently commit a running transaction, and according to the manual they do not belong inside one.

Emulated and native preparation

Not every prepared statement is actually prepared in the database. With emulation, PDO inserts the escaped values into the SQL text itself and sends the result as a single query. According to the manual, the MySQL driver works this way by default; the PDO::ATTR_EMULATE_PREPARES option exists only for the OCI, Firebird and MySQL drivers. SQLite always prepares in the database.

For you as a developer this has three practical consequences:

  • Protection against injection remains as long as you use placeholders. With MySQL, specify the character set in the DSN (charset=utf8mb4) so PDO and the server work with the same encoding.
  • With emulation, syntax errors only show up at execute(), not at prepare().
  • With emulation, reusing a named placeholder is allowed; without it, it is not. Code that relies on this breaks when the setting changes.

Whether you switch emulation off is a trade-off, not an obligation. What matters is that the setting is chosen deliberately and is the same in development, testing and production.

Typical mistakes

  • Putting input into the SQL text by concatenation or sprintf() “because it is only a number”. Later it no longer is.
  • Taking column names for sorting or filtering straight from $_GET instead of choosing them from an allow-list.
  • Setting the error mode to silent and not checking return values, so the code simply carries on after a failure.
  • Running several related changes without a transaction.
  • Showing the message of a PDOException to the user.
  • Trying to prevent duplicate entries in code only, rather than with a UNIQUE constraint in the database; why that fails under concurrent access is shown in preventing duplicate processing of webhooks.

Common misconceptions

They protect the values passed as placeholders. Put column names, sort direction or table names from the request into the SQL text and the hole has merely moved.

OWASP explicitly advises against relying on escaping: it depends on the database and character set, and it is easily forgotten. A placeholder separates code and data by design.

PDO unifies the PHP functions, not the SQL language. Constructs such as ON CONFLICT or INSERT IGNORE remain specific to one database.

A placeholder in ORDER BY runs without error and still does not sort. Check the result, not just the absence of an exception.

Further sources

About the author

Fabian Lücker is managing partner of PHP Schmiede KG in Rheine and has worked in software development since 2007. He is responsible for development and design, and writes here about decisions that come up in real projects.