DB
DB is a static class wrapping one or more named PDO connections. Every query is
parameterized — there's no query builder object between you and the SQL, just placeholders and an
array of bound values.
Configuration
DB::configure('default', ['dsn' => $dsn, 'username' => $user, 'password' => $pass]);
// Optional named contexts, for an app talking to more than one database:
DB::configure('analytics', ['dsn' => $analyticsDsn, 'username' => ..., 'password' => ...]);
Called once from config/bootstrap.php. Most methods take an optional trailing $context to target a non-default connection.
Queries
DB::run(string $query, array $params = [], ?string $context = null): PDOStatement
DB::fetch(int $fetchMode = PDO::FETCH_ASSOC): array // the last run() statement's next row
DB::fetchAll(int $fetchMode = PDO::FETCH_ASSOC): array // the last run() statement's remaining rows
DB::run('SELECT id, email FROM users WHERE role = ?', ['admin']);
$admins = DB::fetchAll();
Writes
DB::insert(string $table, array $data, int $idType = DB::ID_TYPE_UUID, ?string $context = null): string
DB::update(string $table, array $data, array $where = [], ?string $context = null): int // rows updated
DB::delete(string $table, array $where = [], ?string $context = null): int // rows deleted
DB::lastInsertId(): string
DB::rowCount(): int
$id = DB::insert('products', ['name' => 'Widget', 'price' => 10]); // DB::ID_TYPE_UUID by default
DB::update('products', ['active' => false], ['name' => 'Widget']);
DB::delete('products', ['price' => ['BETWEEN', [20, 50]]]);
The $where array DSL
insert()'s sibling write methods accept more than plain equality:
['id' => '123']—WHERE id = ?['age' => ['>', 18]]— any comparison operator['id' => ['IN', [1, 2, 3]]]/['NOT IN', ...]['name' => ['LIKE', '%value%']]['age' => ['BETWEEN', [18, 65]]]['deleted_at' => ['IS', 'NULL']]
Transactions
DB::beginTransaction(?string $context = null): bool
DB::commit(?string $context = null): bool
DB::rollBack(?string $context = null): bool
Connections
DB::connect(?string $context = null): PDO // lazily connects on first use, then reuses it
DB::useConnection(PDO $pdo, string $context = 'default'): void // inject an already-open connection (tests)
DB::disconnect(?string $context = null): void
Next steps
- Schema — creating and altering the tables
DBqueries. - Migration — running schema changes in order, with rollback.
- Service Container — why
DBis called statically with no configuration container.