PHP Advent

#[Language]

PHP PDO: Prepared Statements, Fetching, and Transactions

By Rodney Renner ·

A brass pneumatic tube terminal and steel sorting chute mounted on a slate wall sit above two glass capsules carrying brass cylinders and an open ledger of box-and-line diagrams.

Use PDO with exception-based error handling, associative fetches, native prepared statements, and parameterized queries to read and write MySQL or PostgreSQL databases safely in PHP 8.0 and newer. Always separate SQL structure from user-supplied values with prepare() and execute(), and wrap multi-step writes in beginTransaction(), commit(), and rollBack().

PHP Data Objects (PDO) gives applications a consistent API across relational drivers for MySQL, MariaDB, PostgreSQL, and SQLite, so you can move between them without rewriting query code. Its connection defaults and parameter handling deserve attention even if a framework writes the queries for you. Fetch modes affect the types your PHP code receives, and transaction handling determines what happens when a write fails. Getting these details right helps prevent type bugs and SQL injection vulnerabilities.

Connecting to MySQL and PostgreSQL with PDO

Every connection starts with a Data Source Name (DSN), credentials, and driver options passed to new PDO() (or PDO::connect() in PHP 8.4 and newer). As documented in the PHP manual on PDO connections, PDO::__construct() always throws a PDOException when connecting fails, regardless of your configured error mode.

MySQL and MariaDB Connection Setup

For MySQL or MariaDB on PHP 8.0 and newer, specify charset=utf8mb4 directly in the DSN and pass three attributes in the options array:

<?php

declare(strict_types=1);

$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=shop;charset=utf8mb4';
$dbUser = getenv('DB_USER') ?: 'shop_user';
$dbPassword = getenv('DB_PASSWORD') ?: '';

$pdo = new PDO($dsn, $dbUser, $dbPassword, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
]);

Setting charset=utf8mb4 in the DSN prevents older server defaults from truncating four-byte Unicode characters or introducing encoding mismatches, a topic covered further in the archive guide to character sets from form to database. For MySQL 8 servers using caching_sha2_password, PHP 7.4.4 and newer support the authentication plugin natively through mysqlnd.

PostgreSQL Connection Setup

PostgreSQL uses the pgsql: prefix with host, port, database name, and optional TLS settings such as sslmode=require:

<?php

declare(strict_types=1);

$dsn = 'pgsql:host=127.0.0.1;port=5432;dbname=shop;sslmode=prefer';
$dbUser = getenv('DB_USER') ?: 'shop_user';
$dbPassword = getenv('DB_PASSWORD') ?: '';

$pdo = new PDO($dsn, $dbUser, $dbPassword, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

Check these PostgreSQL details when deploying across PHP versions:

  • If you embed user=... or password=... inside the pgsql: DSN string, PHP 8.4.0 and newer give those DSN values priority over the $username and $password constructor arguments, reversing the precedence used in PHP 8.3 and earlier. Keep credentials in the constructor arguments rather than duplicating them in the DSN.
  • PDO converts semicolons in a PostgreSQL DSN into spaces before handing the string to libpq, so database names or passwords containing semicolons cannot be placed inside the DSN. PHP 8.4.0 and newer also require libpq 10.0 or later.

Declare ext-pdo alongside ext-pdo_mysql or ext-pdo_pgsql so Composer verifies extension presence on target hosts, as outlined in our guide to Composer platform requirements and audits.

Driver Subclasses and PDO::connect() in PHP 8.4+

PHP 8.4 introduced driver-specific subclasses (Pdo\Mysql, Pdo\Pgsql, Pdo\Sqlite, and others) along with the static factory PDO::connect(). According to the PHP PDO::connect manual, calling PDO::connect() returns an instance of the matching driver subclass when one exists:

<?php

declare(strict_types=1);

// Requires PHP 8.4+
$pdo = PDO::connect(
    'mysql:host=127.0.0.1;dbname=shop;charset=utf8mb4',
    getenv('DB_USER') ?: 'shop_user',
    getenv('DB_PASSWORD') ?: '',
    [
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]
);

if ($pdo instanceof Pdo\Mysql) {
    // Access MySQL-specific constants and methods cleanly
}

Use PDO::connect() if your codebase requires PHP 8.4 or newer. If you still support PHP 8.1, 8.2, or 8.3, continue using new PDO() with explicit options.

PDO uses driver-specific SQL parsers to locate parameter markers in PHP 8.4 and newer. In PHP 8.5.0, the older global constants PDO::MYSQL_ATTR_* and PDO::PGSQL_ATTR_DISABLE_PREPARES are deprecated in favor of Pdo\Mysql::ATTR_* and Pdo\Pgsql::ATTR_DISABLE_PREPARES.

Error Handling and Exception Safety

PDO supports three error reporting modes through PDO::ATTR_ERRMODE:

  • PDO::ERRMODE_SILENT: Sets internal error codes without throwing or emitting warnings; you must check return values and call errorInfo() manually.
  • PDO::ERRMODE_WARNING: Emits a PHP E_WARNING while allowing execution to continue.
  • PDO::ERRMODE_EXCEPTION: Throws a PDOException containing a SQL-92 SQLSTATE code and driver details.

As noted in the PHP manual on PDO error handling, PDO::ERRMODE_EXCEPTION became the default in PHP 8.0.0 (earlier PHP versions defaulted to PDO::ERRMODE_SILENT). Set PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION explicitly if your code still targets PHP 7.4 or shares code with PHP 7.x, where silent mode is the default. The option also makes the intended behavior clear to reviewers.

Never let an unhandled PDOException print a stack trace to end users. When PDO::__construct() or PDO::connect() fails, the backtrace can expose database hostnames, usernames, or passwords if display_errors is enabled. Set display_errors = 0 in production php.ini, log the full exception privately, and inspect $e->getCode() when your code needs to recover from expected constraint errors:

<?php

declare(strict_types=1);

function registerAccount(PDO $pdo, string $email, string $passwordHash): void
{
    $stmt = $pdo->prepare(
        'INSERT INTO users (email, password_hash) VALUES (:email, :password_hash)'
    );

    try {
        $stmt->execute([
            'email' => $email,
            'password_hash' => $passwordHash,
        ]);
    } catch (PDOException $e) {
        // MySQL 1062 or PostgreSQL SQLSTATE 23505 identifies a duplicate key.
        $mysqlDuplicate = (string) $e->getCode() === '23000'
            && (int) ($e->errorInfo[1] ?? 0) === 1062;
        if ($mysqlDuplicate || (string) $e->getCode() === '23505') {
            throw new DomainException('An account with that email already exists.', 0, $e);
        }

        throw $e;
    }

}

When reading errorInfo() on a PDO or PDOStatement object, index 0 holds the five-character SQLSTATE code, index 1 holds the driver-specific error number (for example MySQL error 1062), and index 2 holds the driver error message. For generated IDs, MySQL can use lastInsertId() after an AUTO_INCREMENT insert; PostgreSQL can return the ID from INSERT ... RETURNING id with fetchColumn().

Emulated Versus Native Prepared Statements

The attribute PDO::ATTR_EMULATE_PREPARES controls whether PDO substitutes escaped values on the PHP client (true) or attempts to use the driver's native prepared statements (false). The PHP PDO_MYSQL driver documentation states that PDO_MYSQL enables emulated prepares by default. Drivers can differ in their support for this option, so check the driver documentation when configuring PostgreSQL.

For MySQL, setting PDO::ATTR_EMULATE_PREPARES => false has several practical effects:

  1. Emulated prepare() does not contact the server, so a SQL error can surface at execute() instead. With native preparation, many syntax errors surface at prepare(), although driver behavior varies.
  2. A named marker used twice in one statement is allowed only in emulated mode. Use distinct names such as :sender_id and :recipient_id for portable queries.
  3. An array passed to execute() treats its values as strings. Bind LIMIT and OFFSET values explicitly with PDO::PARAM_INT when the query needs integer parameters.

According to the PDO attribute documentation, a driver may fall back to emulation when it cannot prepare a particular query natively, even when the attribute is false. Test the behavior of the driver and SQL you deploy.

Two separate glass feed rails deliver solid brass and copper parameter cylinders into a machined steel query block beside a brass alignment frame on a dark oak bench.

Prepared Statements and Bound Values

Prepared statements separate the query command from its data values. The PHP manual on prepared statements explains how parameter markers avoid manual quoting and escaping. Native prepares can also allow the driver and server to reuse query plans across executions; the effect depends on the driver and workload.

Passing an Array to execute()

For SELECT, INSERT, UPDATE, and DELETE queries with string or numeric filter values, you can pass an array to execute():

<?php

declare(strict_types=1);

// Positional (?) placeholders
$stmt = $pdo->prepare('SELECT id, email, role FROM users WHERE status = ? AND role = ?');
$stmt->execute(['active', 'editor']);
$editors = $stmt->fetchAll();

// Named (:key) placeholders (colons in the array keys are optional)
$stmt = $pdo->prepare('SELECT id, email FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();

execute($params) binds every value in $params as PDO::PARAM_STR. The number of array entries must match the placeholders in the SQL string. Extra keys cause execution to fail.

Explicit Types with bindValue()

When a query requires a strict integer (LIMIT, OFFSET), an explicit NULL, or a boolean (especially in PostgreSQL, where 'false' as a string or '' for boolean false behaves differently from a boolean bind), call bindValue() with a PDO::PARAM_* constant:

<?php

declare(strict_types=1);

function fetchRecentOrders(PDO $pdo, bool $onlyPaid, int $limit, int $offset): array
{
    $stmt = $pdo->prepare(
        'SELECT id, total_cents, created_at
         FROM orders
         WHERE is_paid = :paid
         ORDER BY created_at DESC
         LIMIT :limit OFFSET :offset'
    );

    $stmt->bindValue(':paid', $onlyPaid, PDO::PARAM_BOOL);
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();

    return $stmt->fetchAll();
}

PDO::PARAM_INT does not validate the input. PDO does not reject a numeric string like '1a' before casting it internally, so validate and type-hint integers in PHP (int $limit) before binding.

Repeated Execution with bindParam()

bindValue() evaluates and binds a value when you call it, so it accepts literals, expressions, and constants. bindParam() binds a PHP variable by reference and reads its value when execute() runs. You can change the variable between executions without preparing the query again:

<?php

declare(strict_types=1);

$stmt = $pdo->prepare('INSERT INTO tags (slug, label) VALUES (:slug, :label)');
$slug = '';
$label = '';
$stmt->bindParam(':slug', $slug, PDO::PARAM_STR);
$stmt->bindParam(':label', $label, PDO::PARAM_STR);

foreach ($tagsToInsert as $slug => $label) {
    $stmt->execute();
}

Because bindParam() requires a variable reference, passing a literal such as $stmt->bindParam(':slug', 'php') fails with a fatal error. Do not use bindParam() inside a foreach loop to bind the loop value variable and then call execute() after the loop ends; every bound parameter would hold the final iteration's value. Reusing a single prepared statement across a batch also makes query overhead easier to inspect with PHP profiling with Xdebug or SPX.

SQL Injection Boundaries: What PDO Does and Does Not Protect

Prepared statement placeholders protect data literals (WHERE email = ?, VALUES (:name, :price)). They do not accept SQL identifiers or syntax fragments:

  • Table names (FROM ?) and column names (ORDER BY ?) cannot be parameterized.
  • Sort directions (ASC or DESC) and SQL keywords cannot be bound as parameters.
  • A single placeholder cannot expand into multiple items inside IN (?).
  • Wrapping a placeholder inside quotes (LIKE '%?%') turns ? into literal text rather than a parameter marker.
  • PDO escapes quotes in bound values, not LIKE pattern wildcards (% and _).

Before and After: Safe Dynamic Sorting and Filtering

Consider a product search endpoint that lets callers filter by category IDs, search by name fragment, and choose a sort column and direction.

Here is the unsafe version that interpolates query structure directly:

<?php

// Before: SQL injection via unvalidated identifiers and broken LIKE/IN handling
$sort = $_GET['sort'] ?? 'name';
$dir = $_GET['dir'] ?? 'ASC';
$search = $_GET['q'] ?? '';
$categoryIds = $_GET['categories'] ?? [];

$inList = implode(',', $categoryIds);
$sql = "SELECT id, name, price_cents
        FROM products
        WHERE category_id IN ($inList)
          AND name LIKE '%$search%'
        ORDER BY $sort $dir";

$products = $pdo->query($sql)->fetchAll();

This version allows SQL injection through $sort, $dir, $categoryIds, and $search, and fails with a SQL syntax error whenever $categoryIds is empty.

Here is the safe version using strict identifier allowlists, escaped LIKE wildcards, and dynamically generated placeholders:

<?php

declare(strict_types=1);

function searchProducts(
    PDO $pdo,
    array $rawCategoryIds,
    string $searchTerm,
    string $sortInput,
    string $dirInput
): array {
    // 1. Map external sort input to fixed SQL columns and directions
    $sortColumn = match ($sortInput) {
        'price' => 'price_cents',
        'newest' => 'created_at',
        default => 'name',
    };
    $sortDirection = strtoupper($dirInput) === 'DESC' ? 'DESC' : 'ASC';

    // 2. Reject invalid IDs and handle empty lists before building IN (...)
    $categoryIds = [];
    foreach ($rawCategoryIds as $rawId) {
        $id = filter_var($rawId, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
        if ($id === false) {
            throw new InvalidArgumentException('Category IDs must be positive integers.');
        }
        $categoryIds[] = $id;
    }

    if ($categoryIds === []) {
        return [];
    }

    $placeholders = implode(', ', array_fill(0, count($categoryIds), '?'));

    // 3. Escape literal LIKE wildcards (% and _) with ! before wrapping in %...%
    $escapedSearch = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $searchTerm);
    $likePattern = '%' . $escapedSearch . '%';

    $sql = "SELECT id, name, price_cents
            FROM products
            WHERE category_id IN ($placeholders)
              AND name LIKE ? ESCAPE '!'
            ORDER BY $sortColumn $sortDirection";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([...$categoryIds, $likePattern]);

    return $stmt->fetchAll();
}

The refactored query allows only fixed sort columns and directions into the SQL string. It rejects malformed category IDs, returns no rows for an empty category list, and binds every search value through a ? placeholder. Also avoid hyphens in named placeholders (:user-id fails in PDO; use underscores such as :user_id).

A machined steel gauge plate holds matching square, round, triangular, and hexagonal brass blocks in fitted cutouts beside a wooden tray of rejected rough iron scraps.

Fetching Results Efficiently

By default, PDO sets PDO::ATTR_DEFAULT_FETCH_MODE to PDO::FETCH_BOTH, which duplicates every column under both its column name and a zero-based integer index. Set PDO::FETCH_ASSOC as the connection default to avoid that extra memory overhead. Most PHP applications read rows by column name.

Single Rows, Streams, and Bounded Lists

Choose the fetch call based on result size:

  • **fetch()**: Returns the next row as an associative array (or your chosen fetch style), or false when no rows remain. Check if ($row === false) before reading keys.
  • **fetchAll()**: Loads every remaining row into memory as an array. Use it only for bounded queries with a LIMIT or known small tables.
  • **while ($row = $stmt->fetch()) or foreach ($stmt as $row)**: Processes one row at a time in PHP. The driver may still buffer the full result internally; MySQL buffered queries do so by default.

For PostgreSQL queries that return huge datasets in PHP 8.5.0 and newer, setting PDO::ATTR_PREFETCH to 0 enables lazy single-row fetching. In that mode, finish reading a result before starting another statement on the same connection, because the driver discards unread rows.

Scalar Columns, Key Pairs, and Objects

These fetch modes let you retrieve a scalar, a lookup map, or grouped rows without reshaping nested arrays in PHP loops:

<?php

declare(strict_types=1);

// 1. Single scalar count (returns string|int|false)
$countStmt = $pdo->prepare('SELECT COUNT(*) FROM orders WHERE user_id = :user_id');
$countStmt->execute(['user_id' => $userId]);
$orderCount = (int) $countStmt->fetchColumn();

// 2. Lookup map: [id => name]
$mapStmt = $pdo->query('SELECT id, name FROM categories ORDER BY name');
$categoriesById = $mapStmt->fetchAll(PDO::FETCH_KEY_PAIR);

// 3. Grouped rows by first column: ['paid' => [101, 104], 'pending' => [105]]
$groupStmt = $pdo->query('SELECT status, id FROM orders');
$idsByStatus = $groupStmt->fetchAll(PDO::FETCH_COLUMN | PDO::FETCH_GROUP);

Do not use fetchColumn() to read a boolean column. As the PHP manual explains, a returned false could mean either a database boolean false or an empty result set. Call fetch(), check $row === false, and then inspect the row array.

When mapping rows onto a domain class or DTO with PDO::FETCH_CLASS, PDO assigns column values to properties before running __construct() unless you combine it with PDO::FETCH_PROPS_LATE. If your model uses constructor property promotion or backed enums (PHP 8.1+), fetch an associative array and construct the object explicitly. This gives PHPStan and your constructor full type guarantees when you convert trusted status columns with backed PHP enums. On PostgreSQL, bytea columns return PHP stream resources, which you read with stream_get_contents().

Transactions: Commit, Rollback, and Implicit Commits

PDO opens connections in auto-commit mode, where every single statement commits immediately. As explained in the PHP manual on PDO transactions, calling $pdo->beginTransaction() suspends auto-commit until you finish with $pdo->commit() or $pdo->rollBack().

Always wrap transactional work in try / catch (Throwable $e), check $pdo->inTransaction() before rolling back, and rethrow the original exception:

<?php

declare(strict_types=1);

function transferBalance(PDO $pdo, int $fromId, int $toId, int $amountCents): void
{
    if ($amountCents <= 0) {
        throw new InvalidArgumentException('Transfer amount must be positive.');
    }

    $pdo->beginTransaction();

    try {
        $debit = $pdo->prepare(
            'UPDATE accounts SET balance_cents = balance_cents - :amount
             WHERE id = :id AND balance_cents >= :min_balance'
        );
        $debit->execute([
            'amount' => $amountCents,
            'id' => $fromId,
            'min_balance' => $amountCents,
        ]);

        if ($debit->rowCount() !== 1) {
            throw new RuntimeException('Insufficient funds or missing source account.');
        }

        $credit = $pdo->prepare(
            'UPDATE accounts SET balance_cents = balance_cents + :amount WHERE id = :id'
        );
        $credit->execute([
            'amount' => $amountCents,
            'id' => $toId,
        ]);

        if ($credit->rowCount() !== 1) {
            throw new RuntimeException('Missing destination account.');
        }

        $pdo->commit();
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        throw $e;
    }
}

Checking $pdo->inTransaction() before $pdo->rollBack() protects you when an earlier failure or database disconnect already ended the transaction; calling rollBack() without an active transaction always throws a PDOException even if ATTR_ERRMODE is not set to exceptions. That second exception can hide the original failure. PDO also rolls back any open transaction started via beginTransaction() automatically when the script finishes or the connection closes, whereas raw SQL START TRANSACTION queries bypass PDO's internal state tracking.

Two brass-framed cylindrical glass reservoirs connected by a lower pipe and an upper steel locking lever hold golden amber fluid at equal levels on a dark oak bench.

Transaction behavior also depends on the database engine:

  • Legacy MyISAM tables do not support transactions. beginTransaction() returns true without error, and rollBack() silently leaves every write committed. Confirm every transactional table uses InnoDB.
  • Executing Data Definition Language statements (CREATE TABLE, DROP TABLE, ALTER TABLE, TRUNCATE TABLE) inside a MySQL transaction forces an immediate implicit COMMIT, so a later rollBack() cannot undo earlier writes. Keep schema migrations separate from application transactions. PostgreSQL supports transactional DDL, though keeping schema changes out of application request transactions remains safer across drivers.

Enable PDO::ATTR_PERSISTENT => true only if you manage connection state and pooling. Persistent connections can retain session settings, temporary tables, or locks across requests. The PHP session security guide shows PDO in authentication code and custom database session storage.