PDO (PHP Data Objects) is the modern database abstraction layer for MySQL, PostgreSQL, SQLite, and others. It replaces deprecated mysql_* functions with a consistent API and prepared statement support.
Connection (real project)
$pdo = new PDO(
'mysql:host=127.0.0.1;dbname=app;charset=utf8mb4',
'user',
'pass',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
Why PDO
- Prepared statements reduce SQL injection risk
- Exceptions on failure (
ERRMODE_EXCEPTION) - Swappable drivers for different databases
Playground note
This runner has no live database. Practice query structure with mock result arrays; run PDO against local MySQL/MariaDB or SQLite when ready.
Important interview questions and answers
- Q: PDO vs mysqli?
A: PDO supports multiple drivers and a lean OOP API; mysqli is MySQL-specific with async features—PDO is the default recommendation for portable apps. - Q: Why ERRMODE_EXCEPTION?
A: Failures become catchable exceptions instead of silent false returns.
Self-check
- What DSN string component selects the database type?
- Why set default fetch mode to associative arrays?
Interview prep
- Why PDO ERRMODE_EXCEPTION?
Database failures throw catchable exceptions instead of returning false silently—easier to log and handle in production.