← Back to PHP Course | Chapter 11: Database | Lesson 3 of 21

PHP PDO Introduction

What is PDO?

PDO (PHP Data Objects) provides a single, consistent object-oriented API for talking to many different database systems — MySQL, PostgreSQL, SQLite, and more — so switching databases later doesn't mean rewriting all your query code.

Example: What is PDO?

php
<?php
$pdo = new PDO('sqlite::memory:');
echo get_class($pdo);
// The same PDO API works for MySQL, PostgreSQL, SQLite, and more
?>

PDO Error Modes

You create a PDO connection with new PDO($dsn, $user, $password), where the DSN (Data Source Name) string specifies the database driver and connection details, like 'mysql:host=localhost;dbname=myapp'.

Example: PDO Error Modes

php
<?php
// On a real server: new PDO('mysql:host=localhost;dbname=myapp', $user, $password);
$pdo = new PDO('sqlite::memory:');
echo "Connected via DSN";
?>

Executing Queries (query)

PDO supports named placeholders (:name) and positional placeholders (?) in prepared statements, giving you flexibility in how you bind values compared to mysqli's more rigid parameter binding.

Example: Executing Queries (query)

php
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->exec("CREATE TABLE users (id INTEGER, name TEXT)");
$stmt = $pdo->prepare("INSERT INTO users (id, name) VALUES (:id, :name)");
$stmt->execute(['id' => 1, 'name' => 'Alice']);
echo "Inserted using named placeholder";
?>

Executing Statements (exec)

Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION makes PDO throw real exceptions on database errors instead of silently returning false, which is strongly recommended since it makes failures impossible to accidentally ignore.

Example: Executing Statements (exec)

php
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    $pdo->exec("SELECT * FROM nonexistent_table");
} catch (PDOException $e) {
    echo "Caught exception instead of a silent failure";
}
?>

Closing PDO Connections

Because PDO abstracts over multiple database engines, many teams choose it over mysqli by default even for MySQL-only projects, simply for its more consistent and modern API and easier future portability.

Example: Closing PDO Connections

php
<?php
$pdo = new PDO('sqlite::memory:');
echo "PDO's consistent API is why many teams pick it even for MySQL-only projects";
$pdo = null; // closes the connection
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.