1-Byte
1-Byte Bespoke tools & code

PHP

PDO Bootstrap (db.php pattern)

PHP

A drop-in <code>db.php</code> style file that sets up PDO with sensible defaults: exceptions, strict error mode, UTF-8 and a small helper to reuse the connection across your codebase.

Usage notes

Save this as /config/db.php and adjust the DSN, user and password to match your environment.

  • Call db() whenever you need a PDO instance. It is cached in a static variable to avoid reconnecting on every call.
  • Errors are thrown as exceptions and also logged via error_log().
  • Default fetch mode is associative arrays to keep templates and APIs straightforward.

Copy this snippet into your project

Use the full version for learning, or copy it without comments when you just want the bare code.

<?php
// /config/db.php — PDO bootstrap
declare(strict_types=1);

function db(): PDO
{
    static $pdo = null;

    if ($pdo instanceof PDO) {
        return $pdo;
    }

    $host    = 'localhost';
    $dbname  = 'your_database';
    $user    = 'your_user';
    $pass    = 'your_password';
    $charset = 'utf8mb4';

    $dsn = "mysql:host={$host};dbname={$dbname};charset={$charset}";

    try {
        $pdo = new PDO($dsn, $user, $pass, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ]);
    } catch (PDOException $e) {
        error_log('[DB] Connection failed: ' . $e->getMessage());
        http_response_code(500);
        exit('Database connection error.');
    }

    return $pdo;
}
      

Tags

#php #pdo #database #db.php
← Back to all snippets