Cheat Sheets & Quick References

PDO Quick Reference for PHP Developers

A compact guide to PDO connections, prepared statements, fetching results and handling database errors safely.

Overview

PDO provides a consistent interface for accessing databases from PHP. It supports prepared statements and multiple database drivers, making it a useful foundation for database code.

Create a connection

$pdo = new PDO(
    'mysql:host=localhost;dbname=app_db;charset=utf8mb4',
    $username,
    $password,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

Use prepared statements

$stmt = $pdo->prepare('SELECT id, email FROM users WHERE id = :id');
$stmt->execute(['id' => $userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

Important reminders

Use placeholders for values, not SQL identifiers. Validate and allow-list dynamic column names or sort directions. Choose an explicit fetch mode and error mode. Handle exceptions at an application boundary and avoid exposing database details to visitors.

Official resource

PDO manual: https://www.php.net/manual/en/book.pdo.php