TExcelTAD
Home › PHP › PHP PDO & SQLite

PHP PDO & SQLite

Almost every real PHP application stores its data in a database. PHP ships with PDO (PHP Data Objects), a single, object-oriented API that talks to many database engines — MySQL, MariaDB, PostgreSQL, SQLite, SQL Server and more. You learn one set of methods and only the connection string changes when you switch databases.

In this course we use SQLite, a tiny database engine that lives inside PHP itself. With the special name sqlite::memory: the whole database exists in RAM for the lifetime of the script, so every playground starts with an empty, private database — perfect for learning.

Why PDO?

Feature What it gives you
One API for many databases query(), prepare(), execute() and fetch() work the same everywhere
Prepared statements Safe handling of user input — no SQL injection (next lesson)
Exceptions Errors can be thrown as PDOException, so you can't silently ignore them
Flexible fetching Rows as associative arrays, objects, single columns or key/value pairs
Transactions beginTransaction(), commit(), rollBack()

Note: You may also see the older mysqli_* functions in tutorials. They only work with MySQL. PDO is the more portable choice and the one modern frameworks build on.

Connecting

A connection is a PDO object. Its first argument is a DSN (Data Source Name) that names the driver and where the database is. For MySQL you would also pass a user name and password:

php
<?php
// MySQL / MariaDB on a server
$pdo = new PDO('mysql:host=localhost;dbname=shop;charset=utf8mb4', 'shop_user', 'secret');

// SQLite stored in a file next to the script
$pdo = new PDO('sqlite:shop.db');

// SQLite kept in memory (used in every playground of this course)
$pdo = new PDO('sqlite::memory:');

Right after connecting, set two options that every project should use: throw exceptions on errors, and return rows as associative arrays by default.

php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:', options: [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

echo "Connected using the ", $pdo->getAttribute(PDO::ATTR_DRIVER_NAME), " driver\n";
Connected using the sqlite driver

Creating a table and adding rows

exec() runs an SQL statement that returns no rows (CREATE, INSERT, UPDATE, DELETE) and returns the number of affected rows. lastInsertId() tells you the id the database generated for the last insert.

php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$pdo->exec('CREATE TABLE books (
    id     INTEGER PRIMARY KEY AUTOINCREMENT,
    title  TEXT NOT NULL,
    author TEXT NOT NULL,
    pages  INTEGER
)');

$added = $pdo->exec("INSERT INTO books (title, author, pages) VALUES
    ('The Clockwork Garden', 'Mara Lind', 312),
    ('Salt and Static', 'Ivo Brandt', 198),
    ('Northern Lanterns', 'Mara Lind', 421)");

echo "Rows inserted: $added\n";
echo "Last id: ", $pdo->lastInsertId(), "\n";
Rows inserted: 3
Last id: 3

Reading rows

query() runs a SELECT and returns a PDOStatement. You can loop over it directly with foreach, or call one of the fetch methods:

Method Returns
fetch() the next row, or false when there are no more
fetchAll() all remaining rows as an array
fetchColumn() one column of the next row (first column by default)
fetchAll(PDO::FETCH_KEY_PAIR) [firstColumn => secondColumn, ...]
fetchAll(PDO::FETCH_COLUMN) a flat list of the first column
php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:', options: [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec('CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, author TEXT, pages INTEGER)');
$pdo->exec("INSERT INTO books (title, author, pages) VALUES
    ('The Clockwork Garden', 'Mara Lind', 312),
    ('Salt and Static', 'Ivo Brandt', 198),
    ('Northern Lanterns', 'Mara Lind', 421)");

// 1. Loop over the statement
foreach ($pdo->query('SELECT title, pages FROM books ORDER BY pages') as $row) {
    printf("%-22s %4d pages\n", $row['title'], $row['pages']);
}

// 2. A single value
$total = $pdo->query('SELECT SUM(pages) FROM books')->fetchColumn();
echo "Total pages: $total\n";

// 3. Key/value pairs
$byId = $pdo->query('SELECT id, title FROM books')->fetchAll(PDO::FETCH_KEY_PAIR);
print_r($byId);
Salt and Static         198 pages
The Clockwork Garden    312 pages
Northern Lanterns       421 pages
Total pages: 931
Array
(
    [1] => The Clockwork Garden
    [2] => Salt and Static
    [3] => Northern Lanterns
)

Tip: SQLite returns numbers as PHP int/float in PHP 8.1 and later, so $row['pages'] above is a real integer.

Handling errors

With ERRMODE_EXCEPTION, a broken query throws a PDOException. Catch it, log the details, and show the user a friendly message — never the raw SQL error in production.

php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL)');

try {
    $pdo->query('SELECT * FROM authors');
} catch (PDOException $e) {
    echo "Query failed: ", $e->getMessage(), "\n";
}

try {
    $pdo->exec('INSERT INTO books (title) VALUES (NULL)');
} catch (PDOException $e) {
    echo "Insert failed (SQLSTATE ", $e->getCode(), ")\n";
}
Query failed: SQLSTATE[HY000]: General error: 1 no such table: authors
Insert failed (SQLSTATE 23000)

Transactions

A transaction groups several statements so that they either all succeed or none do. If something fails half-way, rollBack() undoes everything since beginTransaction().

php · try it yourself
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE accounts (name TEXT PRIMARY KEY, balance INTEGER CHECK (balance >= 0))');
$pdo->exec("INSERT INTO accounts VALUES ('ana', 100), ('ben', 20)");

function transfer(PDO $pdo, string $from, string $to, int $amount): void {
    $pdo->beginTransaction();
    try {
        $pdo->exec("UPDATE accounts SET balance = balance + $amount WHERE name = '$to'");
        $pdo->exec("UPDATE accounts SET balance = balance - $amount WHERE name = '$from'");
        $pdo->commit();
        echo "Moved $amount from $from to $to\n";
    } catch (PDOException $e) {
        $pdo->rollBack();
        echo "Transfer of $amount cancelled\n";
    }
}

transfer($pdo, 'ana', 'ben', 30);
transfer($pdo, 'ben', 'ana', 500);   // would make ben negative

foreach ($pdo->query('SELECT * FROM accounts ORDER BY name') as $row) {
    echo $row['name'], ': ', $row['balance'], "\n";
}
Moved 30 from ana to ben
Transfer of 500 cancelled
ana: 70
ben: 50

Notice that the second transfer had already added 500 to Ana's balance before the check failed — the rollback undid it.

Note: Building SQL by inserting variables into the string, as transfer() does, is only acceptable here because the values come from our own code. For anything that comes from a user, use prepared statements — the topic of the next lesson.

Test yourself

Which DSN creates a temporary SQLite database that exists only while the script runs?

  1. sqlite:memory
  2. sqlite::memory:
  3. mysql:memory
  4. sqlite:temp.db

What does $pdo->exec('DELETE FROM books') return?

  1. A PDOStatement
  2. The deleted rows
  3. The number of affected rows
  4. Always true

Which option makes PDO throw a PDOException when a query fails?

  1. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  2. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
  3. PDO::ATTR_PERSISTENT => true
  4. PDO::ATTR_EMULATE_PREPARES => false