The Analogy: The Drilling Jig on the Workbench
In a metal workshop, a machinist who must drill the same pattern of holes into a hundred identical brackets does not measure and mark each one by hand. Instead they build a jig: a fixed metal template that clamps over the workpiece and guides the drill to exactly the right spots every time. Setting up the jig takes effort once, but after that each bracket is loaded, drilled through the guides, and unloaded in seconds. A prepared statement is that jig: the database parses and plans the SQL command once, and then each execution just loads fresh values and runs.
The jig has clamps sized to hold the workpiece firmly. A good machinist sets the clamp to match the material -- tight for thin sheet, wider for a thick block -- so the part cannot shift under the drill. Binding a parameter with an explicit type is the same act of matching the clamp to the material: telling the database that this value is an integer, not a string, so it is held and interpreted correctly. Get the clamp right and the hole lands true; leave it loose and the part can move.
Some jigs are built to hold a variable number of pieces at once -- a rail with three clamp positions today, five tomorrow. The machinist adds exactly as many clamps as there are parts in this batch. When a query must match a list of values whose length is not known in advance, you build exactly that many placeholders on the fly, one clamp per value, and the jig fits the batch precisely.
The failure mode is loading the jig wrong. If you clamp a workpiece that is the wrong size for the guides, or try to run a batch through a jig with no clamps set at all, the drill bites into empty air or wanders off the mark. A prepared statement executed with the wrong number of values, or a dynamic list that turns out to be empty, produces exactly this kind of jammed, malformed operation. The jig only protects you when the workpiece and the clamps genuinely match what the template expects.
Syntax or Core Structure
The core rhythm is prepare once, then bind and execute many times. bindValue attaches a specific value to a placeholder, and its optional third argument declares the type. Reusing the same prepared statement across a loop lets the database skip re-parsing the SQL each time.
<?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 scores (id INTEGER PRIMARY KEY, player TEXT, points INTEGER)');
$ins = $pdo->prepare('INSERT INTO scores (player, points) VALUES (:player, :points)');
$data = ['Ada' => 90, 'Ben' => 75, 'Cara' => 88];
foreach ($data as $player => $points) {
$ins->bindValue(':player', $player);
$ins->bindValue(':points', $points, PDO::PARAM_INT);
$ins->execute();
}
echo 'rows inserted: ', $pdo->query('SELECT COUNT(*) FROM scores')->fetchColumn(), "\n";
$top = $pdo->prepare('SELECT player FROM scores WHERE points >= :min ORDER BY points DESC');
$top->bindValue(':min', 80, PDO::PARAM_INT);
$top->execute();
echo 'top: ', implode(', ', $top->fetchAll(PDO::FETCH_COLUMN)), "\n";
Output:
rows inserted: 3
top: Ada, Cara
One INSERT statement is prepared and then executed three times, once per player, with the points bound as an integer via PDO::PARAM_INT. The SELECT is prepared separately and asks for players scoring at least 80, ordered high to low: Ada at 90 and Cara at 88 qualify, Ben at 75 does not. Preparing the insert once and reusing it is both faster and cleaner than building three separate statements.
Technical Depth: Binding, Types, and Dynamic Lists
bindValue versus bindParam
bindValue takes a snapshot of the value at the moment you call it. bindParam binds the variable itself by reference, so the value read at execute time is whatever the variable holds then. This distinction matters inside loops: with bindParam you can change the variable between executions and each run picks up the current value.
| Method | Binds | Read at | Typical use |
|---|---|---|---|
bindValue | The value now | Bind time | One-off values, literals |
bindParam | The variable by reference | Execute time | Looping with a changing variable |
execute([...]) | All values at once | Execute time | The common, concise case |
<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->exec('CREATE TABLE t (n INTEGER)');
$stmt = $pdo->prepare('INSERT INTO t (n) VALUES (:n)');
$n = 1;
$stmt->bindParam(':n', $n, PDO::PARAM_INT);
$n = 10; $stmt->execute();
$n = 20; $stmt->execute();
$stmt2 = $pdo->prepare('INSERT INTO t (n) VALUES (:n)');
$v = 100;
$stmt2->bindValue(':n', $v, PDO::PARAM_INT);
$v = 999; $stmt2->execute();
$all = $pdo->query('SELECT n FROM t ORDER BY n')->fetchAll(PDO::FETCH_COLUMN);
echo 'stored: ', implode(', ', $all), "\n";
Output:
stored: 10, 20, 100
The bindParam call ties the placeholder to the variable $n. Because the value is read at execute time, the two executions store 10 and 20 -- the values $n held at each execute, not the 1 it held when bound. The bindValue call, by contrast, froze 100 at bind time, so changing $v to 999 afterwards has no effect. Understanding this prevents a whole class of "why is the same value repeated" bugs.
A dynamic IN clause
A placeholder cannot expand into a list, so WHERE code IN (?) binds a single value, not many. To match a variable-length list you generate one placeholder per element and splice those placeholders -- never the values -- into the SQL.
<?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 cities (code TEXT, name TEXT)');
$pdo->exec("INSERT INTO cities VALUES ('LON','London'),('PAR','Paris'),('NYC','New York'),('TYO','Tokyo')");
$wanted = ['LON', 'TYO', 'NYC'];
$holes = implode(', ', array_fill(0, count($wanted), '?'));
$sql = "SELECT name FROM cities WHERE code IN ($holes) ORDER BY name";
$stmt = $pdo->prepare($sql);
$stmt->execute($wanted);
echo 'sql: ', $sql, "\n";
echo 'hits: ', implode(', ', $stmt->fetchAll(PDO::FETCH_COLUMN)), "\n";
Output:
sql: SELECT name FROM cities WHERE code IN (?, ?, ?) ORDER BY name
hits: London, New York, Tokyo
array_fill produces one ? per wanted code, and implode joins them into ?, ?, ?. Only the placeholders are built into the SQL text; the actual codes are still passed to execute as bound values, so the query stays injection-safe. The three requested codes resolve to London, New York, and Tokyo, sorted by name.
Binding a LIKE pattern
For a partial-match search, bind the whole pattern -- including the % wildcards -- as the value. The wildcards belong to the data you supply, not to the SQL text.
<?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 fruit (name TEXT)');
$pdo->exec("INSERT INTO fruit VALUES ('apple'),('apricot'),('banana'),('grape')");
$term = 'ap';
$stmt = $pdo->prepare('SELECT name FROM fruit WHERE name LIKE ? ORDER BY name');
$stmt->execute([$term . '%']);
echo 'starts with ap: ', implode(', ', $stmt->fetchAll(PDO::FETCH_COLUMN)), "\n";
$stmt->execute(['%p%']);
echo 'contains p: ', implode(', ', $stmt->fetchAll(PDO::FETCH_COLUMN)), "\n";
Output:
starts with ap: apple, apricot
contains p: apple, apricot, grape
The first execution binds ap%, matching names that start with those letters -- apple and apricot. The second reuses the same prepared statement with %p%, matching any name containing a p, which adds grape. Because the pattern is a bound value, a user searching for a literal % cannot alter the query structure.
Real World Example: A Filtered Catalog Search
A product catalog often lets shoppers filter by several categories at once and cap the price. That means a query with a dynamic IN list plus a fixed price bound -- exactly the mix of variable-length and fixed parameters that prepared statements handle well. The Catalog class below seeds some items and exposes a search method built entirely from placeholders.
<?php
declare(strict_types=1);
final class Catalog
{
public function __construct(private PDO $pdo)
{
$this->pdo->exec(
'CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, cat TEXT, price INTEGER)'
);
$rows = [
['Notebook', 'stationery', 300],
['Pencil', 'stationery', 80],
['Router', 'hardware', 4500],
['Cable', 'hardware', 250],
['Mug', 'kitchen', 600],
];
$ins = $this->pdo->prepare('INSERT INTO items (name, cat, price) VALUES (?, ?, ?)');
foreach ($rows as $r) {
$ins->execute($r);
}
}
/** @param string[] $cats */
public function search(array $cats, int $maxPrice): array
{
$holes = implode(', ', array_fill(0, count($cats), '?'));
$sql = "SELECT name, price FROM items
WHERE cat IN ($holes) AND price <= ?
ORDER BY price";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([...$cats, $maxPrice]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
$pdo = new PDO('sqlite::memory:', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$cat = new Catalog($pdo);
foreach ($cat->search(['stationery', 'hardware'], 1000) as $row) {
echo $row['name'], ': ', $row['price'], "\n";
}
Output:
Pencil: 80
Cable: 250
Notebook: 300
The constructor loads five items across three categories. search builds one placeholder per requested category, then appends a final ? for the price cap, and passes all the values in order using the spread operator [...$cats, $maxPrice]. Filtering for stationery and hardware under 1000 returns Pencil, Cable, and Notebook, sorted by price -- the Router at 4500 is too dear and the Mug is in an unrequested category. Every value, list or scalar, arrives as a bound parameter, so the search cannot be injected.
The design flaw hides in the empty case. If search is called with an empty $cats array -- a shopper who clears every category filter -- then array_fill produces zero placeholders and the SQL becomes WHERE cat IN () AND price <= ?, which is a syntax error in most databases and will throw. The method silently assumes at least one category is always chosen, an assumption the UI may not guarantee. A robust version must special-case the empty list explicitly: either skip the IN clause entirely when no categories are selected, or decide that "no filter" means "match nothing" and return early. Leaving the empty list to fall through to malformed SQL turns an ordinary user action into a runtime crash.
Common Mistakes
- Trying to bind a list to a single placeholder.
WHERE id IN (?)with an array does not expand into many values. Generate one placeholder per element and bind them individually.
- Splicing the IN values instead of the placeholders. Build
?, ?, ?into the SQL, then pass the actual values toexecute. Putting the values themselves into the string reopens the injection hole.
- Putting wildcards in the SQL for LIKE. Writing
LIKE '%?%'treats the whole thing as a literal string, not a placeholder. Bind the pattern%term%as the value instead.
- Confusing
bindParamwithbindValuein a loop.bindParamreads the variable at execute time, so a stale or shared variable can store the wrong value. PreferbindValueor pass values toexecuteunless you specifically want reference behaviour.
- Re-preparing the same SQL inside a loop. Preparing once and executing many times is the whole point. Re-calling
preparewith the same string on every iteration throws the performance benefit away.
- Assuming the default type is always fine. Values bind as strings unless you say otherwise. For
LIMITand other spots where the database is strict about integers, passPDO::PARAM_INTexplicitly.
- Forgetting emulation differences. With emulated prepares on, PDO may accept things a real prepare rejects, hiding bugs until production. Know your
ATTR_EMULATE_PREPARESsetting.
- Mismatching the number of values and placeholders. Passing four values to a statement with three placeholders throws. Build the value list from the same source as the placeholders so they cannot drift apart.
- Letting an empty dynamic list produce
IN (). A cleared filter that yields zero placeholders makes malformed SQL. Handle the empty case explicitly rather than letting it crash.
Best Practices
- Prepare a statement once and execute it repeatedly for batches, letting the database reuse its parsed plan.
- Declare the parameter type with
PDO::PARAM_INTand friends whenever the column or clause is type-sensitive, such asLIMIT.
- For an
INlist, generate placeholders witharray_fillandimplode, and bind the values -- never the raw list -- to keep the query safe.
- Bind
LIKEpatterns, wildcards included, as the parameter value so the search stays parameterised.
- Prefer passing all values to
execute([...])for clarity, reservingbindParamfor the rare case where reference semantics are actually wanted.
- Build the placeholder string and the value array from one source, so their lengths always match.
- Special-case the empty dynamic list before building the SQL, deciding deliberately whether it means "no filter" or "match nothing".
- Know your
ATTR_EMULATE_PREPARESsetting and test against the same configuration you deploy with, so emulation quirks do not surprise you.
Practice Exercises
- Create a
readingstable and insert six rows by preparing oneINSERTand executing it in a loop, binding the numeric column withPDO::PARAM_INT. Confirm the count is six.
- Write a function
findByIds(PDO $pdo, array $ids): arraythat builds a dynamicINclause of placeholders, binds the ids as values, and returns the matching rows. Test it with a three-element and a one-element list.
- Implement a case-insensitive search over a
namestable usingLIKE, binding the pattern%term%as the value, and show it matching entries that contain the term anywhere.
- Demonstrate the
bindParamreference trap: bind a variable, execute, change the variable, execute again, and print the two stored rows to show that execute-time reading produced two different values from one bind call.