PHP — PDO

🐘 PHP 8.2+ 🟢 Lesson 34 of 52 📂 Phase 12: Database with PDO 📅 2026 Edition
📌 Covered in this chapter: PDO ante enti? · Database connection · DSN · Prepared statements · Binding values · execute · Fetching rows · Fetch modes · CRUD · Transactions · PDO exceptions

Welcome to PHP — PDO in our PHP Complete Masterclass! Connect to MySQL databases using PDO (PHP Data Objects), binding parameters safely with prepared statements.

1Database Access with PDO (PHP Data Objects)

PDO (PHP Data Objects) is a database abstraction layer that provides a uniform, secure API to connect to MySQL, PostgreSQL, SQLite, and SQL Server databases in PHP.

🛡️ Preventing SQL Injection with Prepared Statements

NEVER concatenate user input directly into SQL strings! Always use PDO Prepared Statements with parameterized bindings (e.g. :email or ?). This completely neutralizes SQL injection attacks.

PHP — PDO Connection & Prepared Statement Query ▶ Run Code
<?php
$dsn = "mysql:host=localhost;dbname=our_compiler;charset=utf8mb4";
$user = "db_user";
$password = "SecretPass123!";

try {
    $pdo = new PDO($dsn, $user, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);

    // Prepared Statement
    $stmt = $pdo->prepare("SELECT id, name, email FROM users WHERE role = :role");
    $stmt->execute(['role' => 'admin']);
    $admins = $stmt->fetchAll();

    foreach ($admins as $admin) {
        echo "Admin: " . htmlspecialchars($admin['name']) . "<br>";
    }
} catch (PDOException $e) {
    die("Database Connection Error: " . $e->getMessage());
}
?>
💻 Live PHP Code Execution

Test and run this PHP script in our online web compiler environment:

Open in Online PHP Compiler →
OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on PHP 8.2+ · Last updated August 2026