6 min read
Working with Databases: PDO
Prerequisites: Generators & yield
PDO (PHP Data Objects) is PHP's standard database abstraction — the same API works across MySQL, PostgreSQL, SQLite, and others.
$pdo = new PDO('sqlite:app.db');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([1]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$insert = $pdo->prepare('INSERT INTO users (name) VALUES (:name)');
$insert->execute(['name' => 'Ada']);
Common mistakes
- Building a query with string concatenation
(
"...WHERE id = " . $userInput) instead of a prepared statement's?/:nameplaceholders — this opens the door to SQL injection, covered fully in Level 3's Security Fundamentals.