Databases with PDO — PHP

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…

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.");
}

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
$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:

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

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.)

💡 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.";
}

⚠️ Leaky queries and doubled results

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.

What you will learn