PDO Basics in PHP

From the PHP cheat sheet · Database & PDO · verified Jul 2026

PDO Basics

Connecting to databases and executing queries

php
// Connect to database
$pdo = new PDO(
    'mysql:host=localhost;dbname=mydb',
    'username',
    'password'
);

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

// Insert data
$stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (?, ?)');
$stmt->execute([$name, $email]);
💡 Always use prepared statements to prevent SQL injection
⚡ Use transactions for related operations
📌 PDO supports multiple databases with same interface
🔥 Set PDO::ERRMODE_EXCEPTION for better error handling
Back to the full PHP cheat sheet