The Analogy: The Bank Teller Window and the Vault
A bank keeps its cash and its ledgers in a secured vault at the back of the building. The clerks who serve customers never walk into that vault themselves. Every request -- a deposit, a withdrawal, a balance check -- passes through a standard teller window. The teller is trained on one fixed protocol, and that same protocol works whether the branch runs an old manual vault or a new electronic one. The clerk at the counter does not need to know which vault is installed; they just follow the window's procedure. PHP Data Objects, or PDO, is that teller window: one uniform way to talk to a database, whether the vault behind it is MySQL, PostgreSQL, or SQLite.
The window has a printed request slip with fixed boxes. When a customer wants to move money, the clerk writes the account number in the account box and the amount in the amount box. Crucially, the teller reads the values from those boxes and feeds them into the vault machinery through separate controls. The customer's handwriting never becomes part of the machine's instructions -- it is only ever data dropped into a labelled slot. This is exactly what a prepared statement with placeholders does: the SQL command is fixed in advance, and the values are handed over separately, so a value can never be mistaken for a command.
Results come back from the window in a controlled shape. Sometimes the teller hands back a single record -- one account's details. Sometimes they hand back a whole stack of matching records. Sometimes they hand back just one figure, like a balance total. And if something is wrong -- the account is frozen, the vault is jammed -- a good teller says so plainly, with a clear message, rather than silently sliding back an empty envelope and leaving the clerk to guess. PDO offers exactly these shapes: fetch one row, fetch all rows, fetch a single column value, and, when configured for exceptions, raise a loud error the moment anything fails.
The danger appears when a lazy teller abandons the boxed slip and instead copies the customer's freehand note straight onto the vault's command tape. A customer who writes "withdraw fifty AND unlock every drawer" now has that whole note executed as instructions, because the teller pasted words meant as data into the place where commands live. The boxes existed precisely to keep the customer's words as data and never as commands. This is SQL injection: the instant you splice raw input into the text of a query, any visitor can smuggle instructions into your vault. Every rule in this lesson exists to keep the boxed slip and never touch the command tape.
Syntax or Core Structure
You connect by constructing a PDO object with a data source name, or DSN, that names the driver and target. Then you set two attributes that every project should turn on: exceptions for errors, and associative arrays as the default row shape. From there, you prepare a statement with ? placeholders, execute it with the values, and iterate the results.
<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, city TEXT)');
$insert = $pdo->prepare('INSERT INTO users (name, city) VALUES (?, ?)');
$insert->execute(['Ada', 'London']);
$insert->execute(['Ben', 'Paris']);
$insert->execute(['Cara', 'London']);
$stmt = $pdo->prepare('SELECT id, name FROM users WHERE city = ?');
$stmt->execute(['London']);
foreach ($stmt as $row) {
echo $row['id'], ': ', $row['name'], "\n";
}
Output:
1: Ada
3: Cara
The connection string sqlite::memory: asks for a throwaway in-memory database, ideal for demonstration; a real app would use something like mysql:host=localhost;dbname=app. The ? placeholders in the prepared INSERT are filled by the array passed to execute, once per row. The SELECT uses the same placeholder mechanism, and because a PDOStatement is iterable, foreach walks the matching rows directly. Ben is in Paris, so only Ada and Cara -- the two Londoners -- appear, keeping their original ids 1 and 3.
Technical Depth: Placeholders, Fetch Shapes, and Error Modes
Two kinds of placeholder
PDO accepts positional placeholders, written ?, and named placeholders, written :label. Positional placeholders are filled by a plain array in order; named placeholders are filled by an associative array keyed on the label. Named placeholders are clearer when a query has many parameters, or when the same value is used twice. You cannot mix the two styles in one statement.
| Style | In SQL | Bound with | Best when |
|---|---|---|---|
| Positional | WHERE a = ? AND b = ? | [$a, $b] (order matters) | Few parameters, short queries |
| Named | WHERE a = :a AND b = :b | [':a' => $a, ':b' => $b] | Many parameters, or reused values |
A placeholder can only ever stand for a single scalar value. It cannot hold a column name, a table name, or a piece of SQL such as ORDER BY. Those are structural and must come from your own code, never from user input, because there is no safe way to bind them.
Fetching in different shapes
Once a statement has executed, you choose how to pull the data back. fetch returns the next single row (or false when exhausted). fetchAll returns every remaining row in one array. fetchColumn returns just one column from the next row, which is perfect for aggregates like COUNT(*). Passing PDO::FETCH_COLUMN to fetchAll flattens a single-column result into a plain list of values.
<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price INTEGER)');
$rows = [['Pen', 150], ['Pad', 300], ['Ink', 900]];
$ins = $pdo->prepare('INSERT INTO products (name, price) VALUES (?, ?)');
foreach ($rows as [$n, $p]) {
$ins->execute([$n, $p]);
}
$one = $pdo->query('SELECT name, price FROM products ORDER BY id')->fetch();
echo 'first: ', $one['name'], ' ', $one['price'], "\n";
$count = $pdo->query('SELECT COUNT(*) FROM products')->fetchColumn();
echo 'count: ', $count, "\n";
$names = $pdo->query('SELECT name FROM products ORDER BY name')->fetchAll(PDO::FETCH_COLUMN);
echo 'names: ', implode(', ', $names), "\n";
$stmt = $pdo->prepare('SELECT name FROM products WHERE price >= :min');
$stmt->execute([':min' => 300]);
echo 'dear: ', implode(', ', $stmt->fetchAll(PDO::FETCH_COLUMN)), "\n";
Output:
first: Pen 150
count: 3
names: Ink, Pad, Pen
dear: Pad, Ink
Here query is used for the fixed, input-free statements -- it runs SQL immediately and is safe only because no user data touches it. The aggregate comes back through fetchColumn as the scalar 3. The name list is sorted alphabetically by the database and flattened by FETCH_COLUMN. The final query uses a named placeholder :min and returns only products priced at 300 or above, Pad and Ink.
Why the error mode matters
By default, older PDO configurations could fail silently, returning false from a method and leaving you to check by hand. Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION -- which is the default from PHP 8.0 on -- makes every failure throw a PDOException. That means a broken query stops execution loudly instead of letting a false slip downstream and cause a confusing error much later. Combined with try/catch, it gives you one clear place to handle database trouble.
Prepared statements versus string concatenation
The single most important reason to use PDO correctly is to defeat SQL injection. When you build a query by gluing user input into the SQL text, a crafted value can change what the query means. A placeholder stops this because the value is sent to the database separately from the compiled command, so it can only ever be treated as data.
<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, secret TEXT)');
$pdo->exec("INSERT INTO users (name, secret) VALUES ('admin', 'TOP'), ('guest', 'low')");
$evil = "nobody' OR '1'='1";
$sql = "SELECT name, secret FROM users WHERE name = '" . $evil . "'";
$rows = $pdo->query($sql)->fetchAll();
echo 'concat rows: ', count($rows), "\n";
foreach ($rows as $r) {
echo ' leaked: ', $r['name'], '/', $r['secret'], "\n";
}
$stmt = $pdo->prepare('SELECT name, secret FROM users WHERE name = ?');
$stmt->execute([$evil]);
$safe = $stmt->fetchAll();
echo 'prepared rows: ', count($safe), "\n";
Output:
concat rows: 2
leaked: admin/TOP
leaked: guest/low
prepared rows: 0
The attacker's value nobody' OR '1'='1 closes the quote early and appends an always-true condition. Spliced into the string, it turns a lookup for one name into a query that matches every row, leaking both users and their secrets. The prepared version treats the entire string, quotes and all, as one literal name to search for -- no user is called nobody' OR '1'='1, so it correctly returns zero rows. The command never changed; only the data did.
Real World Example: A Member Directory Repository
A common pattern is to wrap a table behind a small class that hides the SQL and exposes plain methods -- register, findByEmail, count. The class receives its PDO connection through the constructor, so it never opens its own, and every method uses prepared statements. This keeps the data-access logic in one place and the rest of the application free of raw queries.
<?php
declare(strict_types=1);
final class MemberDirectory
{
public function __construct(private PDO $pdo)
{
$this->pdo->exec(
'CREATE TABLE members (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL
)'
);
}
public function register(string $name, string $email): int
{
$stmt = $this->pdo->prepare(
'INSERT INTO members (name, email) VALUES (:name, :email)'
);
$stmt->execute([':name' => $name, ':email' => $email]);
return (int) $this->pdo->lastInsertId();
}
public function findByEmail(string $email): ?array
{
$stmt = $this->pdo->prepare(
'SELECT id, name, email FROM members WHERE email = ?'
);
$stmt->execute([$email]);
$row = $stmt->fetch();
return $row === false ? null : $row;
}
public function count(): int
{
return (int) $this->pdo->query('SELECT COUNT(*) FROM members')->fetchColumn();
}
}
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$dir = new MemberDirectory($pdo);
$id1 = $dir->register('Ada Lovelace', 'ada@example.com');
$id2 = $dir->register('Ben Adams', 'ben@example.com');
echo "registered ids: $id1, $id2\n";
echo 'members: ', $dir->count(), "\n";
$found = $dir->findByEmail('ben@example.com');
echo 'lookup: ', $found['name'], "\n";
$missing = $dir->findByEmail('nobody@example.com');
echo 'missing: ', var_export($missing, true), "\n";
$dir->register('Ada Byron', 'ada@example.com');
echo 'members now: ', $dir->count(), "\n";
$dup = $dir->findByEmail('ada@example.com');
echo 'which ada? ', $dup['name'], "\n";
Output:
registered ids: 1, 2
members: 2
lookup: Ben Adams
missing: NULL
members now: 3
which ada? Ada Lovelace
The constructor builds the table and stores the injected connection, so the directory owns its schema but not its transport. register uses named placeholders and returns the new row's id via lastInsertId, giving the caller ids 1 and 2. findByEmail returns a typed ?array -- a row for Ben, and null for an address that does not exist, which var_export prints as NULL. count reads a single scalar through fetchColumn. Every query that touches the $email value binds it as a parameter, so the directory is injection-safe by construction.
The design flaw is subtler than a syntax problem: the members table has no UNIQUE constraint on email, and findByEmail uses fetch, which quietly returns only the first matching row. Registering a second ada@example.com succeeds -- the count climbs to three -- and the later lookup silently returns the original Ada Lovelace, hiding the duplicate entirely. The code looks correct and never errors, yet it has allowed two accounts to share an email and then masked the ambiguity. The fix belongs in the schema and the query together: add UNIQUE(email) so the database rejects the second insert with a PDOException, and treat "one row expected" as a contract the lookup should defend, not an assumption it silently trusts.
Common Mistakes
- Concatenating user input into SQL. Building a query with
"... WHERE id = " . $_GET['id']is the classic injection hole. Always use a placeholder and bind the value, no matter how "safe" the input looks.
- Believing
quote()or manual escaping is enough. Hand-escaping is error-prone and driver-specific. Prepared statements are the only reliable defence, so reach for them by default rather than patching strings.
- Trying to bind a column or table name. A placeholder can hold a value, never an identifier or a fragment of SQL like
ORDER BY name. Whitelist such structural pieces in your own code instead.
- Leaving the error mode at silent. Without
ERRMODE_EXCEPTION, a failing call returnsfalseand the problem surfaces far away. Set exception mode so failures throw immediately at the point of trouble.
- Ignoring the difference between
fetchandfetchAll. CallingfetchAllon a huge result loads every row into memory at once. Iterate withfetchorforeachwhen the set could be large.
- Assuming
fetchreturningfalsemeans an error.falsefromfetchsimply means no more rows. Distinguish "no results" from "query failed" -- the latter throws when exceptions are on.
- Reusing one statement across unrelated queries. Each distinct SQL string should be its own prepared statement. Re-preparing the same string in a loop, however, wastes work; prepare once, execute many times.
- Interpolating with the deprecated
mysql_*mindset. The oldmysql_queryfunctions are gone. Do not port their string-building habits to PDO; the whole point is to separate command from data.
- Forgetting to handle the connection failing. Constructing
PDOcan throw if the database is unreachable. Wrap it where appropriate and never expose the raw exception message, which may reveal credentials, to end users.
Best Practices
- Turn on
PDO::ERRMODE_EXCEPTIONandPDO::FETCH_ASSOCat construction, so every connection fails loudly and returns predictable rows.
- Use prepared statements with placeholders for every query that includes a value, without exception, treating string concatenation as a bug.
- Choose named placeholders for queries with several parameters, and positional
?for short ones, keeping the binding easy to read.
- Prepare a statement once and execute it repeatedly when inserting or updating many rows, rather than re-preparing inside the loop.
- Pick the fetch shape that matches the need --
fetchfor streaming,fetchAllfor small sets,fetchColumnfor single scalars.
- Wrap a table behind a small repository class that receives its
PDOby injection, so data access lives in one testable place.
- Enforce real constraints in the schema --
NOT NULL,UNIQUE, foreign keys -- rather than trusting application code to keep data honest.
- Never leak raw database error messages to users; log the detail server-side and show a generic message, since exceptions can expose structure and credentials.
Practice Exercises
- Create an in-memory SQLite table of books with
titleandyear, insert four rows using a single prepared statement executed in a loop, and print the titles published after 1950 using a named placeholder.
- Write a function that takes a
PDOand an email, looks the user up with a prepared statement, and returns the row ornull. Demonstrate it returningnullfor an address that is not present.
- Take a query that concatenates
$_GET['q']into aLIKEclause and rewrite it to use a placeholder, binding the pattern%term%as the parameter value rather than splicing it into the SQL.
- Build a small repository class for a
taskstable withadd,markDone, andcountOpenmethods, each using prepared statements, and add aUNIQUEconstraint so a duplicate task title is rejected with aPDOException.