Skip to content
Happy Programming Guide
Start learning
PHP

PHP and Databases

Connecting PHP to MySQL or PostgreSQL with PDO: prepared statements, fetching, transactions, error handling and the queries that make pages slow.

A close-up of a printed circuit board

PDO is the way to talk to a database from PHP. It works with MySQL, PostgreSQL, SQLite and others through one API, and its prepared statements remove SQL injection as a category of problem. This guide covers connecting, querying safely, transactions, and the query patterns that decide whether a page loads in 50 milliseconds or two seconds.

Connecting#

PHP
<?php
declare(strict_types=1);

$dsn = sprintf(
    "mysql:host=%s;dbname=%s;charset=utf8mb4",
    getenv("DB_HOST") ?: "localhost",
    getenv("DB_NAME")
);

try {
    $pdo = new PDO($dsn, getenv("DB_USER"), getenv("DB_PASSWORD"), [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ]);
} catch (PDOException $e) {
    error_log($e->getMessage());
    exit("Could not connect to the database.");
}

Those three options are not optional in practice:

  • ERRMODE_EXCEPTION makes failures throw instead of returning false silently. Without it, a broken query looks like an empty result.
  • FETCH_ASSOC returns rows as associative arrays rather than duplicating every column under both a name and a number.
  • EMULATE_PREPARES false sends the statement to the database to be prepared properly, rather than PDO interpolating the values itself.

The charset=utf8mb4 in the DSN matters too — MySQL’s older utf8 cannot store four-byte characters, which includes most emoji.

For PostgreSQL and SQLite the only change is the DSN:

PHP
<?php
$dsn = "pgsql:host=localhost;port=5432;dbname=shop";
$dsn = "sqlite:" . __DIR__ . "/data/app.db";

Querying safely#

PHP
<?php
// Never
$sql = "SELECT * FROM users WHERE email = '$email'";

// Always
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();

An email of ' OR '1'='1 in the first version returns every row. The second sends the query and the data separately, so input cannot change the query’s structure.

Named placeholders read better when there are several:

PHP
<?php
$stmt = $pdo->prepare(
    "INSERT INTO posts (title, body, author_id) VALUES (:title, :body, :author)"
);
$stmt->execute([
    "title"  => $title,
    "body"   => $body,
    "author" => $authorId,
]);

echo $pdo->lastInsertId();
PHP
<?php
$allowed = ["name", "price", "created_at"];
$sort = in_array($_GET["sort"] ?? "", $allowed, true) ? $_GET["sort"] : "name";
$direction = ($_GET["dir"] ?? "") === "desc" ? "DESC" : "ASC";

$stmt = $pdo->query("SELECT * FROM products ORDER BY $sort $direction");

Fetching#

PHP
<?php
$stmt = $pdo->prepare("SELECT id, name, price FROM products WHERE price < ?");
$stmt->execute([20]);

$one = $stmt->fetch();          // the next row, or false
$all = $stmt->fetchAll();       // every remaining row
$column = $stmt->fetchColumn(); // the first column of the next row

// Row by row - constant memory on a large result
foreach ($stmt as $row) {
    echo $row["name"];
}

Two fetch modes worth knowing:

PHP
<?php
// id => name, in one call
$lookup = $pdo->query("SELECT id, name FROM products")
              ->fetchAll(PDO::FETCH_KEY_PAIR);

// A flat array of one column
$names = $pdo->query("SELECT name FROM products")
             ->fetchAll(PDO::FETCH_COLUMN);

Use fetchAll when the result is small and you need it all. For a large export, iterate — fetchAll on a million rows will exhaust memory.

Counting and checking#

PHP
<?php
$count = (int) $pdo->query("SELECT COUNT(*) FROM products")->fetchColumn();

$stmt = $pdo->prepare("UPDATE products SET price = ? WHERE id = ?");
$stmt->execute([9.99, 42]);

echo $stmt->rowCount(), " rows updated";

rowCount() is reliable for INSERT, UPDATE and DELETE. For SELECT it is driver-dependent — count with a COUNT query or with count(fetchAll()) instead.

Transactions#

PHP
<?php
$pdo->beginTransaction();

try {
    $debit = $pdo->prepare(
        "UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?"
    );
    $debit->execute([$amount, $fromId, $amount]);

    if ($debit->rowCount() === 0) {
        throw new RuntimeException("Insufficient funds");
    }

    $credit = $pdo->prepare("UPDATE accounts SET balance = balance + ? WHERE id = ?");
    $credit->execute([$amount, $toId]);

    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    throw $e;
}

Either both updates happen or neither does. Note the balance check inside the WHERE clause — letting the database enforce it avoids a race where two concurrent requests both read a sufficient balance.

Batch inserts#

PHP
<?php
$pdo->beginTransaction();

$stmt = $pdo->prepare("INSERT INTO products (name, price) VALUES (?, ?)");

foreach ($products as $product) {
    $stmt->execute([$product["name"], $product["price"]]);
}

$pdo->commit();

Preparing once and executing many times is considerably faster than preparing each time, and wrapping the loop in a transaction avoids a disk flush per row. Ten thousand inserts can go from minutes to seconds.

The N+1 problem#

This is the most common cause of a slow PHP page:

PHP
<?php
// 1 query for the posts
$posts = $pdo->query("SELECT id, title, author_id FROM posts LIMIT 50")->fetchAll();

foreach ($posts as $post) {
    // ...then 50 more, one per post
    $stmt = $pdo->prepare("SELECT name FROM authors WHERE id = ?");
    $stmt->execute([$post["author_id"]]);
    $post["author"] = $stmt->fetchColumn();
}

Fifty-one queries. Each is fast; the round trips are what cost you. Two fixes:

PHP
<?php
// A join
$sql = "SELECT p.id, p.title, a.name AS author
        FROM posts p
        JOIN authors a ON a.id = p.author_id
        LIMIT 50";
$posts = $pdo->query($sql)->fetchAll();
PHP
<?php
// Or two queries, joined in PHP
$posts = $pdo->query("SELECT id, title, author_id FROM posts LIMIT 50")->fetchAll();

$ids = array_unique(array_column($posts, "author_id"));
$placeholders = implode(",", array_fill(0, count($ids), "?"));

$stmt = $pdo->prepare("SELECT id, name FROM authors WHERE id IN ($placeholders)");
$stmt->execute(array_values($ids));
$authors = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

foreach ($posts as &$post) {
    $post["author"] = $authors[$post["author_id"]] ?? "Unknown";
}
unset($post);

That unset($post) after a foreach by reference is not optional. Without it, $post still points at the last element and the next loop using that variable will corrupt your array — one of PHP’s genuinely nasty traps.

Indexes#

SQL
EXPLAIN SELECT * FROM orders WHERE customer_id = 42 AND status = 'paid';

If the output says the query type is ALL, the database is reading every row. Add an index on the columns you filter and sort by:

SQL
CREATE INDEX idx_orders_customer_status ON orders (customer_id, status);

Column order matters in a composite index: it can serve queries filtering on customer_id alone or on both, but not on status alone.

Also worth doing: select the columns you need rather than SELECT *. Pulling a large text column you never display costs bandwidth and memory on every row.

Error handling#

PHP
<?php
try {
    $stmt = $pdo->prepare("INSERT INTO users (email) VALUES (?)");
    $stmt->execute([$email]);
} catch (PDOException $e) {
    if ($e->getCode() === "23000") {
        exit("That email address is already registered.");
    }

    error_log($e->getMessage());
    exit("Something went wrong. Please try again.");
}

SQLSTATE 23000 is an integrity constraint violation — a duplicate key, usually. Handling it specifically lets you give a useful message rather than a generic failure.

Never show the raw exception message to a visitor. It can contain table names, column names and occasionally the connection string.

Questions people ask#

PDO or mysqli?

PDO. It supports several databases with one API, has named placeholders, and its exception handling is better. mysqli is MySQL-only and offers nothing PDO does not.

Is mysqli_real_escape_string enough?

No. It can protect a correctly quoted value and does nothing for one you forgot to quote, and it depends on the connection charset being right. Prepared statements remove the whole class of mistake instead of mitigating it.

Should I use an ORM?

Eloquent or Doctrine save real effort once you have many tables and relationships. For a handful of queries, PDO directly is simpler and you can see exactly what runs.

How do I see the query PDO actually ran?

With emulation off, PDO never builds the final string — the database does. Turn on the database’s own query log, which shows the truth rather than a reconstruction.

Where to go next#

PHP performance, where database queries dominateRead next

Keep reading

PHP

PHP and AJAX

Send data between JavaScript and PHP without reloading the page: fetch, JSON endpoints, form handling, error responses and CSRF protection.

5 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *