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.
What you will learn
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:
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.
<?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());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():
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:
<?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";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.
<?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));[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
| Mode | Result | Typical use |
|---|---|---|
PDO::FETCH_ASSOC | an array per row, keyed by column name | the normal case |
PDO::FETCH_COLUMN | only the first column, as a flat list | a list of IDs or names |
PDO::FETCH_KEY_PAIR | first column as key, second as value | select lists, lookups |
PDO::FETCH_CLASS | an object of a given class per row | data 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:
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
Common misconceptions
Further sources
- PHP: PDO - Manual overview of PDO in the PHP manual
- PHP: PDO::prepare - Manual placeholders, their rules and limits
- PHP: Errors and error handling - Manual error modes, exceptions by default since PHP 8.0
- PHP: Transactions and auto-commit - Manual autocommit, rollback at script end, DDL
- PHP: PDO::connect - Manual driver-specific subclasses since PHP 8.4
- SQL Injection Prevention - OWASP Cheat Sheet Series defences, allow-lists for identifiers
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.