PDO (PHP Data Objects) is the recommended way to interact with databases in PHP. It supports prepared statements which protect against SQL injection.
Why PDO over mysqli?
- Supports multiple database types (MySQL, PostgreSQL, SQLite, etc.)
- Cleaner API with named placeholders
- Exception-based error handling
Best Practices
- Always use prepared statements with bound parameters
- Set
PDO::ERRMODE_EXCEPTION to catch errors - Use environment variables for credentials — never hardcode them
- Close connections by setting
$pdo = null
Example
<?php
// Connect
try {
$pdo = new PDO(
'mysql:host=localhost;dbname=mydb;charset=utf8mb4',
'username',
'password',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
// SELECT with prepared statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();
// INSERT
$stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)');
$stmt->execute(['name' => $name, 'email' => $email]);