PDO stands for PHP Data Objects and it's a database abstraction layer in PHP. It provides an object-oriented interface to access different types of databases—such as MySQL, PostgreSQL, or SQLite—without needing to change much of your code.
Key Features of PDO:
✅ Consistent API
Same code style regardless of which database you use.
✅ Prepared Statements
Helps prevent SQL injection via bound parameters:
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => $userId]);
✅ Transactions Support
Great for use cases like banking systems or other operations that need rollback/commit.
✅ Exception-based Error Handling
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
✅ Easy Database Switching
Switching from MySQL to PostgreSQL? Usually only the DSN and driver need to be changed.
Example: Connecting to MySQL with PDO
$dsn = 'mysql:host=localhost;dbname=testdb;charset=utf8mb4';
$user = 'root';
$pass = '';
try {
$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully!";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Summary:
PDO is the recommended way to work with databases in modern PHP applications—especially for its security, flexibility, and ease of use.