CodeBlanks Logo Icon CodeBlanks

What is PDO?

PHP course · Advanced · Lesson 1/92

Learn what PDO (PHP Data Objects) is and why it is used.

What is PDO?

PDO (PHP Data Objects) is an object-oriented, unified interface for accessing databases in PHP. The same PHP code works with different databases: MySQL, SQLite, PostgreSQL and more.

PDO is driver-based; each database has its own driver but the calling interface stays the same. mysqli works only with MySQL, while PDO supports many databases.

PDO throws errors as PDOException, so they can be caught with try/catch.

PDO drivers and DSN

In PDO a connection is built with a DSN (Data Source Name) string. The DSN starts with the driver name: mysql:host=localhost;dbname=test, sqlite::memory: or pgsql:host=localhost;dbname=test.

When the driver changes, the rest usually stays the same; the PHP-side code does not change. SQL dialects may still differ; PDO does not translate SQL.

To keep the examples short, this lesson uses in-memory SQLite (sqlite::memory:); it needs no setup and is fast.

Exercise Connect to in-memory SQLite

Connect to in-memory SQLite with PDO: new PDO('sqlite::memory:'). Print the class name of the connection object with get_class().

Show example solution
:memory:');. Print the class name with echo get_class($pdo) . "\n";.
Example solution:
<?php
// Connect to in-memory SQLite with PDO and print the class name

$pdo = new PDO('sqlite::memory:');
echo get_class($pdo) . "\n";

Test yourself

  1. Which PHP extension works with multiple databases (MySQL, SQLite, PostgreSQL) through a unified interface?

    • mysqli
    • PDO
    • mysql_fetch_array
    • preg_match
    Show answer

    PDO — Correct. PDO supports many databases through a unified interface; it connects to different databases via drivers.

  2. Complete the PDO driver

    <?php
    // Supported PDO drivers
    $drivers = ['mysql', '____', 'pgsql'];
    foreach ($drivers as $driver) {
        echo $driver . "\n";
    }
    ?>
    Show answer
    <?php
    // Supported PDO drivers
    $drivers = ['mysql', 'sqlite', 'pgsql'];
    foreach ($drivers as $driver) {
        echo $driver . "\n";
    }
    ?>
  3. Match the PDO concepts

    DSN
    Connection string
    driver
    Database name prefix
    PDOException
    Error exception
    mysqli
    MySQL-only extension

All lessons in Advanced