Running with execute()
Learn to run a prepared statement with parameters using execute().
execute() takes a value array
execute() runs the prepared statement. It takes the values to bind as an array. For example execute(['stationery', 30]) binds two values to two ? placeholders in order.
The order of values in the array matches the left-to-right order of ? placeholders in the template. A wrong order produces wrong results.
This method lets you safely combine several conditions; values are never inserted directly into the SQL text.
The positional ? placeholder
The ? mark is a positional placeholder: it sits in the template where a value goes and is bound in order. For example 'SELECT name FROM products WHERE category = ? AND price >= ?' has two ? marks.
The first ? is for the category, the second for the price. In execute(), the first array value binds to the first ?, the second to the second ?.
The placeholder count must equal the array length; missing or extra values throw an error.
Exercise Filter with two ? placeholders
Build the template 'SELECT name FROM products WHERE category = ? AND price >= ?' with prepare(). Run it with execute(['stationery', 30]). Fetch all rows with fetchAll(PDO::FETCH_ASSOC) and print the name field of each row.
Show example solution
:FETCH_ASSOC). Print with foreach ($rows as $row) { echo $row['name'] . "\n"; }.
Example solution:
<?php
// Run multiple ? placeholders by passing a value array to execute
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, category TEXT, price INTEGER)");
$pdo->exec("INSERT INTO products (name, category, price) VALUES ('Pen', 'stationery', 25)");
$pdo->exec("INSERT INTO products (name, category, price) VALUES ('Notebook', 'stationery', 40)");
$pdo->exec("INSERT INTO products (name, category, price) VALUES ('Chocolate', 'food', 15)");
$stmt = $pdo->prepare("SELECT name FROM products WHERE category = ? AND price >= ?");
$stmt->execute(['stationery', 30]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
echo $row['name'] . "\n";
}
Test yourself
-
Complete the execute() call
$stmt->____(['stationery', 30]);Show answer
$stmt->execute(['stationery', 30]); -
How do parameters match in execute([5, 'a'])?
- They match by key name
- They match in random order
- By the left-to-right order of ? placeholders
- Only the first value is bound
Show answer
By the left-to-right order of ? placeholders — Correct! Positional placeholders match the array values in left-to-right order.
-
Match the concepts
- ?
- Positional placeholder
- :name
- Named placeholder
- [1, 2]
- execute() value array
- PDOStatement
- prepare() return type