By the end of this lesson, your PHP can answer "Which dishes cost $12 or less?" straight from the database: Chicken Noodles, Iced Tea, Crackers. The question is written once, and the number is filled in later. Whatever odd things a visitor types can't be used to break into your database either.
PDO (PHP Data Objects) is PHP's built-in way to talk to a database. MySQL, PostgreSQL and SQLite are all used through the same methods. Picture the storeroom slip at Mrs. Tini's Stall. The slip is pre-printed: "Take ____ from the menu shelf". The waiter only fills in the blank. The storeroom clerk reads what is in the blank as an item name, never as a new instruction. Even if the waiter writes "everything" in the blank, the clerk looks for an item named exactly "everything". In PHP, the thing that works like this slip is called a prepared statement. The query (an SQL command for the database) is written first with blanks, like the pre-printed slip. The values are filled in later, like the blank the waiter fills in, and they are always read as values.
Every example in this lesson uses the menu table of Mrs. Tini's Stall:
| id | name | price |
|---|---|---|
| 1 | Fried Rice | 15 |
| 2 | Chicken Noodles | 12 |
| 3 | Iced Tea | 5 |
| 4 | Crackers | 2 |
Connecting: new PDO
This code connects PHP to a MySQL database named stall:
<?php
$dsn = "mysql:host=localhost;dbname=stall;charset=utf8mb4";
try {
$pdo = new PDO($dsn, "stall_app", "secret", [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
} catch (PDOException $e) {
error_log($e->getMessage());
exit("The service is having trouble. Try again later.");
}
- The first argument is called the DSN (Data Source Name): the kind of database, the server address, the database name and the charset. For SQLite (a database in a single file),
"sqlite:stall.db"is enough, with no user or password. - The second and third arguments are the user and password. The fourth argument is an array of settings.
PDO::FETCH_ASSOCmakes each result row an array with the column names as keys (the Fetch section says why). try { ... } catch (PDOException $e) { ... }: when the code insidetrythrows an exception (an error that can be caught), PHP jumps straight tocatch, and$eholds that error. The details are in the Error Handling lesson.- When the database server is down,
new PDOthrows aPDOExceptionwith a message likeSQLSTATE[HY000] [2002] Connection refused. Write that message to the log (a record on the server that visitors don't see) witherror_log. Don'techoit to visitors, because the message can leak the server address and the database name.
Prepared statements: prepare, then execute
This is the "$12 or less" question, written as a prepared statement:
$stmt = $pdo->prepare("SELECT name, price FROM menu WHERE price <= ?");
$stmt->execute([12]);
$cheap = $stmt->fetchAll();
// Chicken Noodles 12, Iced Tea 5, Crackers 2
prepare()prepares the query with?as a blank (placeholder). It returns aPDOStatementobject, usually kept in$stmt.- SQLite checks the query right away, at
prepare(). With MySQL, PDO's default setting only imitates this step (emulated prepares): the query is sent and checked only atexecute(). execute([12])fills the blanks, in the order of the array, then runs the query. Every value in that array is sent as text (a string).- Placeholders can have names too, like
:max. This is clearer when there are several values:
$stmt = $pdo->prepare("SELECT name, price FROM menu WHERE price <= :max AND name <> :except");
$stmt->execute(["max" => 12, "except" => "Crackers"]);
// Chicken Noodles 12, Iced Tea 5
Why bother? Compare it with gluing the input straight into the query, which $pdo->query() then runs:
$name = $_GET["name"]; // the visitor typed: ' OR '1'='1
$pdo->query("SELECT id, name FROM menu WHERE name = '$name'");
// the SQL becomes: ... WHERE name = '' OR '1'='1' -> 4 rows, the whole menu
$stmt = $pdo->prepare("SELECT id, name FROM menu WHERE name = ?");
$stmt->execute([$name]);
// looks for a dish named exactly ' OR '1'='1 -> 0 rows
In the first version, the quote mark ' in what the visitor typed closes the name text early. The rest is read as part of the SQL command, and '1'='1' is always true, so every row is selected. Input that changes the shape of a query like this is called SQL injection. In the same way, an attacker can read, change or delete data that isn't theirs. With a placeholder, the input is always treated as a value, like the blank on the slip that is always read as an item name. The attack is covered in full in the lesson SQL Injection Prevention in the Security track. The rule here is simple: every value from outside (a form, a URL) goes in through ? or :name, never through "...$variable...".
Two kinds of value need a special way:
- A number for
LIMIT. On MySQL,execute([2])makesLIMIT '2', and MySQL refuses it as a syntax error. - A list for
IN. One?cannot hold an array.
The way to do both:
$stmt = $pdo->prepare("SELECT name FROM menu ORDER BY price LIMIT ?");
$stmt->bindValue(1, 2, PDO::PARAM_INT);
$stmt->execute();
// Crackers, Iced Tea
$ids = [1, 3];
$marks = implode(", ", array_fill(0, count($ids), "?")); // "?, ?"
$stmt = $pdo->prepare("SELECT name FROM menu WHERE id IN ($marks)");
$stmt->execute($ids);
// Fried Rice, Iced Tea
bindValue(1, 2, PDO::PARAM_INT) fills the first ? with 2, and PDO::PARAM_INT sends it as a number, not text. In the second example, array_fill and implode make one ? for each id. $marks holds only ? signs, so gluing it into the query is still safe: the values still go in through execute().
Other options. PDO is not the only way PHP talks to a database:
| Way | Pick it when |
|---|---|
| PDO (used here) | you want one way for many databases, with ? or :max placeholders |
| mysqli | the database is only MySQL, or the code comes from an old tutorial. Use its prepared statements too ($mysqli->prepare with ?) |
| Eloquent (Laravel) or Doctrine (Symfony) | you use a framework. The values still go in through placeholders |
Whichever you use, never glue $_POST into an SQL string. The pattern mysqli_query($conn, "... WHERE name = '$_POST[name]'") from old tutorials opens an SQL injection hole.
Fetch: getting the results
This code gets the dish with id 2 through fetch():
$stmt = $pdo->prepare("SELECT id, name, price FROM menu WHERE id = ?");
$stmt->execute([2]);
print_r($stmt->fetch());
This query asks for three columns, and the connection has no settings yet. Before looking at the result, guess: does the array from this fetch() hold 3 entries or 6?
Array
(
[id] => 2
[0] => 2
[name] => Chicken Noodles
[1] => Chicken Noodles
[price] => 12
[2] => 12
)
Six entries, not three. PDO's default mode is PDO::FETCH_BOTH: every column is stored twice, by column name and by its position number (starting from 0). That's why PDO::FETCH_ASSOC is usually set on the connection, or written right in the call: $stmt->fetch(PDO::FETCH_ASSOC).
| Mode | fetch() returns |
Reading the name |
|---|---|---|
PDO::FETCH_BOTH (default) |
an array, name and number keys | $row["name"] or $row[1] |
PDO::FETCH_ASSOC |
an array, column-name keys | $row["name"] |
PDO::FETCH_NUM |
an array, number keys | $row[1] |
PDO::FETCH_OBJ |
a stdClass object |
$row->name |
fetch()takes one next row. When there are no rows left, or the query found nothing, it givesfalse.fetchAll()takes every row at once, as an array of arrays (one array for each row). When there are no results, it returns an empty array[].- Because
fetch()can givefalse, a function that looks up one record is usually writtenreturn $stmt->fetch() ?: null;.a ?: busesawhenacounts as true, andbwhen it doesn't. So the result is the row it found, ornullwhen there's none. This lesson's exercise uses the same pattern, but not on themenutable: an in-memory SQLite database with auserstable holding Budi, Ani and Citra.findById($pdo, 2)returns Ani's data, and an id that doesn't exist returnsnull. - After an
INSERT,$pdo->lastInsertId()gives the new row's id, as a string.
Errors: PDO::ERRMODE_EXCEPTION
Since PHP 8.0, PDO's default error mode is PDO::ERRMODE_EXCEPTION: a failing query throws a PDOException. So a typo in a table name appears right away. In this code, menu is mistyped as menuu:
<?php
$pdo = new PDO("sqlite:stall.db");
$stmt = $pdo->prepare("SELECT name, price FROM menuu WHERE price <= ?");
The result:
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 1 no such table: menuu in /var/www/stall/menu.php:4
(The message above comes from SQLite. MySQL gives a different code and sentence for the same mistake.)
Uncaughtmeans nocatchcaught that exception, so the script stopped.SQLSTATE[...]is the standard SQL error code, followed by the database's own message.- The old
PDO::ERRMODE_SILENTmode throws nothing:prepare()only returnsfalse, and you have to check for the mistake yourself through$pdo->errorInfo(). That check is easy to miss, so keep exception mode. - Catch
PDOExceptionin the part of the code that can handle it, log$e->getMessage(), and show visitors a general message.
💡 Transactions: all of it or none of it
Say the menu table also has a stock column. An order of 3 Iced Tea (id 3) means two changes: a new row in the orders table, and Iced Tea's stock going down by 3. Both must happen together, or not at all. A transaction wraps both changes into one:
try {
$pdo->beginTransaction();
$pdo->prepare("INSERT INTO orders (menu_id, quantity) VALUES (?, ?)")->execute([3, 3]);
$pdo->prepare("UPDATE menu SET stock = stock - ? WHERE id = ?")->execute([3, 3]);
$pdo->commit();
} catch (PDOException $e) {
$pdo->rollBack();
echo "Failed: " . $e->getMessage();
}
beginTransaction() opens the transaction, commit() saves all its changes, and rollBack() cancels all of them. Say only 2 Iced Tea are left, and the stock column has the rule CHECK (stock >= 0) (stock can't go below 0). The UPDATE fails with SQLSTATE[23000]: Integrity constraint violation: 19 CHECK constraint failed: stock >= 0. rollBack() undoes the INSERT that already ran, so the orders table stays empty and the stock stays at 2. The idea of a transaction is in the lesson Transactions in the SQL track.
The catch in this example is not ready for a real website. echo $e->getMessage() shows the database's message to visitors, which the ⚠️ section below warns against. catch (PDOException $e) also catches only database errors. Any other error isn't caught, so rollBack() doesn't run. The safe version:
try {
$pdo->beginTransaction();
$pdo->prepare("INSERT INTO orders (menu_id, quantity) VALUES (?, ?)")->execute([3, 3]);
$pdo->prepare("UPDATE menu SET stock = stock - ? WHERE id = ?")->execute([3, 3]);
$pdo->commit();
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
error_log($e->getMessage());
echo "Your order failed. Please try again.";
}
Throwablecatches everything PHP can throw,PDOExceptionincluded (covered in the Error Handling lesson).inTransaction()answerstruewhile a transaction is still open. Without this check,rollBack()with no open transaction throwsPDOException: There is no active transaction.
⚠️ Leaky queries and doubled results
- Gluing input into a query.
"... WHERE id = $id"with$idfrom$_GETopens an SQL injection hole. Useprepare()andexecute(). - Forgetting
fetch()can befalse.$stmt->fetch()["name"]for an id that doesn't exist gives a Warning. Check the result first, or turn it intonullwith?: null. - Surprised by doubled entries. The doubled entries come from
PDO::FETCH_BOTH. SetPDO::FETCH_ASSOC. - Showing
$e->getMessage()to visitors. It can hold table names, the query, even the server address. Log it, show a general message.
TL;DR: PDO (PHP Data Objects) connects PHP to a database through new PDO($dsn, $user, $password, $options), where $dsn holds the kind, address and name of the database. Values from outside always go in through placeholders (blanks in the query): $stmt = $pdo->prepare("... WHERE id = ?") then $stmt->execute([$id]), or a named placeholder :max with ["max" => 12]. Gluing input into the query string opens SQL injection: what a visitor types can change the shape of the query. fetch() takes one row (or false), and fetchAll() takes every row. The default mode FETCH_BOTH stores each column twice, so set PDO::FETCH_ASSOC. Since PHP 8.0, PDO::ERRMODE_EXCEPTION is the default: a failing query throws a PDOException (an error you can catch with catch). Its message is written to the log (a record on the server), not shown. Changes that must happen together are wrapped in a transaction: beginTransaction(), then commit(), or rollBack() to cancel all of them when it fails.
⚡ The query first, the values later
Write:
$stmt = $pdo->prepare("SELECT name, price FROM menu WHERE price <= ?");
$stmt->execute([12]);
$cheap = $stmt->fetchAll();
Meaning: $pdo is the connection to the database, made with new PDO(...). prepare() prepares the query (an SQL command) with ? as a blank, called a placeholder. execute([12]) fills the ? with 12 and runs the query, then fetchAll() takes every row of the result. From the menu table of Mrs. Tini's Stall, the result is Chicken Noodles, Iced Tea and Crackers.
⚡ Why it must go through a placeholder
Guess first: the menu table holds 4 dishes, and the query SELECT id, name FROM menu WHERE name = '$name' looks for one dish. A visitor types ' OR '1'='1 as $name, and that input is glued into the query string. How many rows come back?
4 rows, the whole menu, because the input changes the shape of the query into WHERE name = '' OR '1'='1', and '1'='1' is always true. Through prepare and ?, 0 rows: the query looks for a dish named exactly that.
Meaning: Input that changes the shape of a query is called SQL injection. Through this hole, an attacker can read, change or delete data that isn't theirs. So every value from outside goes in through a ? placeholder or a named placeholder like :name, never through "...$variable...".
⚡ fetch stores every column twice
Guess first: the query asks for 3 columns (id, name, price), and the connection has no settings. fetch() takes one row of the result as an array. Does that array hold 3 entries or 6?
Six. The default mode is PDO::FETCH_BOTH: each column is stored twice, by its name and by its position number.
Meaning: Set PDO::FETCH_ASSOC so the keys are column names only. fetch() takes one row, or false when there are no rows left. So a lookup function is usually written return $stmt->fetch() ?: null;. Here ?: turns false into null.