{
    "slug": "pdo",
    "term": "PDO",
    "category": "php",
    "difficulty": "intermediate",
    "short": "PHP Data Objects — a database abstraction layer supporting prepared statements across multiple database drivers.",
    "long": "PDO provides a consistent interface to multiple database backends (MySQL, PostgreSQL, SQLite, etc.) through a unified API. It supports both named (:name) and positional (?) parameter placeholders in prepared statements. PDO::ATTR_EMULATE_PREPARES should be set to false to ensure the database — not PHP — handles the parameterisation. PDO throws PDOException on failure when PDO::ATTR_ERRMODE is set to PDO::ERRMODE_EXCEPTION.",
    "aliases": [
        "PHP PDO",
        "PHP Data Objects",
        "PDO extension"
    ],
    "tags": [
        "php",
        "database",
        "sql-injection",
        "security"
    ],
    "misconception": "Using PDO automatically prevents SQL injection. PDO with prepared statements prevents SQLi, but PDO also supports emulated prepared statements (PDO::ATTR_EMULATE_PREPARES) which do client-side interpolation — always disable emulation and use native prepared statements.",
    "why_it_matters": "PDO is the standard PHP database abstraction layer — it provides prepared statements, consistent error handling, and supports multiple databases with the same API. Using mysql_* functions or raw string concatenation instead is a security and maintainability failure.",
    "common_mistakes": [
        "Using PDO::ERRMODE_SILENT (the default) — errors fail silently and are nearly impossible to debug.",
        "Leaving PDO::ATTR_EMULATE_PREPARES enabled — use native prepared statements for proper SQL injection protection.",
        "Catching PDOException but swallowing it without logging — you lose all diagnostic information.",
        "Creating a new PDO connection on every function call instead of sharing a single connection."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "prepared_statement",
        "sql_injection",
        "mysqli"
    ],
    "prerequisites": [
        "prepared_statement",
        "sql_injection",
        "database_indexing"
    ],
    "refs": [
        "https://www.php.net/manual/en/book.pdo.php"
    ],
    "bad_code": "// Interpolated variables — SQL injection:\n$id = $_GET['id'];\n$stmt = $pdo->query(\"SELECT * FROM users WHERE id = $id\");\n\n// Prepared statement with PDO:\n$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');\n$stmt->execute([':id' => (int)$id]);\n$user = $stmt->fetch(PDO::FETCH_ASSOC);",
    "good_code": "\\$pdo = new PDO(\n    'mysql:host=localhost;dbname=myapp;charset=utf8mb4',\n    \\$_ENV['DB_USER'],\n    \\$_ENV['DB_PASS'],\n    [\n        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,\n        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,\n        PDO::ATTR_EMULATE_PREPARES   => false, // native prepared statements\n    ]\n);\n\n// Named placeholders\n\\$stmt = \\$pdo->prepare('SELECT * FROM users WHERE email = :email AND active = :active');\n\\$stmt->execute([':email' => \\$email, ':active' => 1]);\n\\$user = \\$stmt->fetch();\n\n// Insert + last insert ID\n\\$stmt = \\$pdo->prepare('INSERT INTO orders (user_id, total) VALUES (?, ?)');\n\\$stmt->execute([\\$userId, \\$total]);\n\\$orderId = \\$pdo->lastInsertId();\n\n// Transactions\n\\$pdo->beginTransaction();\ntry { \\$pdo->commit(); } catch (\\Throwable \\$e) { \\$pdo->rollBack(); throw \\$e; }",
    "quick_fix": "Use PDO with ERRMODE_EXCEPTION and EMULATE_PREPARES=false — real prepared statements, not emulated ones, provide true SQL injection protection",
    "severity": "high",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/pdo",
        "html_url": "https://codeclaritylab.com/glossary/pdo",
        "json_url": "https://codeclaritylab.com/glossary/pdo.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[PDO](https://codeclaritylab.com/glossary/pdo) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/pdo"
            }
        }
    }
}