</>
CompilerOnline
Open Interactive Editor

PHP Data Objects (PDO)

PHP PDO

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. This abstraction layer means you can use the same PDO methods to query different database engines.

Prepared Statements

Prepared statements offer major security benefits because they separate SQL structure from raw data inputs, entirely neutralizing SQL injection risks. The database parses and compiles the SQL query structure once, then runs it with parameter values.

PDO handles errors using exceptions, which can be caught in try-catch blocks to prevent connection details and table structures from being leaked to users.

Using fetch modes (like PDO::FETCH_ASSOC or PDO::FETCH_OBJ), developers can retrieve database rows as associative arrays or clean objects matching their code design.

Bound Parameters In PDO

Bound parameters separate data placeholders from the query structure, preventing SQL Injection by preventing raw strings from modifying query intent.

php
<?php
$pdo = new PDO("sqlite::memory:");
$pdo->exec("CREATE TABLE log (msg TEXT)");
$stmt = $pdo->prepare("INSERT INTO log VALUES (?)");
$stmt->execute(["Database Bound Parameter Log!"]);
echo "Data securely written to log!\n";
?>
php
<?php
try {
    $db = new PDO("sqlite::memory:");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec("CREATE TABLE users (id INT, name TEXT)");
    $db->exec("INSERT INTO users VALUES (1, 'Alice')");

    $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([1]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    echo "User name: " . $user['name'] . "\n";
} catch(PDOException $e) {
    echo "DB Error: " . $e->getMessage() . "\n";
}
?>