CodeBlanks Logo Icon CodeBlanks

Connecting with PDO

PHP course · Advanced · Lesson 2/92

Learn to connect to a database with the PDO constructor and a DSN.

The PDO constructor

To connect to PDO write new PDO($dsn, $user, $password). The DSN is the connection string; it starts with a driver name like sqlite::memory:.

SQLite needs no user or password; the DSN alone is enough. For MySQL you write mysql:host=localhost;dbname=test and pass $user and $password arguments.

If the connection fails PHP throws a PDOException.

PDOException and error mode

If something fails while connecting (for example a wrong DSN), PDO throws a PDOException. If not caught the program stops.

Wrap the connection code in try/catch; catch with catch (PDOException $e). Set the error mode with $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION) so query errors also throw exceptions.

To close the connection write $pdo = null; PHP also closes it automatically when the script ends.

Exercise Safe connection with try/catch

Connect to in-memory SQLite with new PDO('sqlite::memory:'). Wrap the connection in try/catch; catch with catch (PDOException $e). On success print 'OK'; on error print the message with $e->getMessage().

Show example solution
:memory:'); and print with echo 'OK' . "\n";. Catch with catch (PDOException $e) and print the message with echo $e->getMessage() . "\n";.
Example solution:
<?php
// Build a safe connection with try/catch
try {
    $pdo = new PDO('sqlite::memory:');
    echo 'OK' . "\n";
} catch (PDOException $e) {
    echo $e->getMessage() . "\n";
}

Test yourself

  1. Complete the PDO constructor call

    <?php
    $dsn = 'sqlite::memory:';
    $pdo = ____($dsn);
    echo get_class($pdo) . "\n";
    ?>
    Show answer
    <?php
    $dsn = 'sqlite::memory:';
    $pdo = new PDO($dsn);
    echo get_class($pdo) . "\n";
    ?>
  2. What should you do when a PDOException is thrown while connecting?

    • Catch it with try/catch
    • Wait for the program to crash
    • Exit immediately with die()
    • Print a warning with echo and continue
    Show answer

    Catch it with try/catch — Correct. try/catch catches the PDOException; the catch block handles the error.

  3. Match the connection concepts

    new PDO($dsn)
    Opens connection
    PDOException
    Connection error
    $dsn
    Connection string
    try/catch
    Catches errors

All lessons in Advanced