Hoppa till innehåll

Pdo V2.0 Extended Features

PDO v2.0 provides improved error handling mechanisms. You can now specify a custom error handler using the setErrorHandler method.

$pdo->setErrorHandler(function ($errno, $errstr, $errfile, $errline) 
    // custom error handling logic
);

PDO v2.0 supports asynchronous queries, which allow you to execute queries in the background without blocking the main thread.

Example:

$stmt = $pdo->prepare('SELECT * FROM large_table');
$stmt->executeAsync();

Classic PDO required manual savepoint management. PDO v2.0 introduces a nested transaction API:

$pdo->beginTransaction();
try 
    // operation A
$pdo->beginTransaction(); // automatically creates a savepoint
try 
    // operation B
    $pdo->commit(); // releases savepoint
 catch (Throwable $e) 
    $pdo->rollBack(); // rolls back to savepoint, not main transaction
$pdo->commit();

catch (Throwable $e) $pdo->rollBack(); pdo v2.0 extended features

The extended feature here is true nesting, not just simulating savepoints.

Before diving into extended features, note v2.0’s foundational changes:


Inserting thousands of rows with individual execute() calls is slow. PDO v2.0 introduces PDOStatement::executeBatch(). PDO v2

In PDO v1, extending the driver was difficult and often required C-level knowledge. PDO v2.0 opens the architecture for developer extensibility.

Developers can now more easily write "Middleware" drivers. For example, one could write a wrapper driver that automatically encrypts specific columns on write and decrypts on read, or a query-logging driver that sits transparently between the application and the database. This allows for Aspect-Oriented Programming (AOP) within the database layer without external libraries.

PDO v2.0 ships with an extended type map that respects database column types:

| Database type | PHP type | |----------------|-------------------| | BIGINT | string or int (if within PHP int range) | | JSON | array (decoded automatically) | | DATETIME | DateTimeImmutable | | ENUM('a','b')| string or actual enum (with schema awareness) | Classic PDO required manual savepoint management

Enable it via attribute:

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_TYPED);
// Now $row['created_at'] is a DateTimeImmutable object

This eliminates manual json_decode() and date string parsing across your application.

A common pattern is fetching a single value or a single row as an array. PDO v2.0 adds shorthand methods to PDOStatement: