PDO Best Practices
Always use prepared statements, set error mode to exceptions, avoid persistent connections in web apps, and wrap PDO in a repository class to isolate database access.
Always use prepared statements, set error mode to exceptions, avoid persistent connections in web apps, and wrap PDO in a repository class to isolate database access.
<?php
// Repository pattern wrapping PDO
class UserRepository {
public function __construct(private PDO $pdo) {}
public function find(int $id): ?array {
$stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = :id LIMIT 1");
$stmt->execute(["id" => $id]);
return $stmt->fetch() ?: null;
}
public function findAll(int $limit = 50, int $offset = 0): array {
$stmt = $this->pdo->prepare("SELECT * FROM users ORDER BY id LIMIT :limit OFFSET :offset");
$stmt->bindValue(":limit", $limit, PDO::PARAM_INT);
$stmt->bindValue(":offset", $offset, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
}
}
Inject PDO into repositories as a dependency — never call new PDO() inside a class method.