Framework Docs Database

Database

The Database class is a fluent PDO query builder that wraps MySQL (and other PDO-compatible databases) with a readable, chainable API. It covers the full CRUD cycle, JOINs, transactions, pagination, and raw queries.

Namespace: Wojo\Database\Database — extends PDO

Getting a Connection

Always use the static factory. The framework manages the singleton internally.

$db = Database::Go();   // returns the shared PDO-extended instance

Reading Data

Method Returns Description
select(string $table, string $columns = '*') self Start a SELECT query
count(string $table, string $column = '*') self SELECT COUNT(column)
first() object|false Run and return first row as object
one() object|false Alias for first()
last() object|false Return last matching row
random() object|false Return a random row
run('select') array Return all matching rows as array of objects
affected() int Row count after run()
exist() bool Returns true if any row matches the current WHERE
PHP
// Fetch one row
$user = Database::Go()->select('users')->where('id', $id)->first();

// Fetch many rows
$posts = Database::Go()->select('posts', 'id, title, created_at')
    ->where('status', 'active')
    ->orderBy('created_at', 'DESC')
    ->limit(10)
    ->run('select');

// Count rows
$total = Database::Go()->count('posts')->where('user_id', $userId)->first();
echo $total->count;  // → integer

Writing Data

Method Signature Description
insert() insert(string $table, array $data): self INSERT a row
update() update(string $table, array $data): self UPDATE rows matched by WHERE
delete() delete(string $table): self DELETE rows matched by WHERE
batch() batch(string $table, array $rows): self Bulk-insert multiple rows
truncate() truncate(string $table): self TRUNCATE a table
getLastInsertId() getLastInsertId(): string PDO lastInsertId() after INSERT
getAllLastInsertId() getAllLastInsertId(): array All IDs inserted in a batch
PHP
// Insert
Database::Go()->insert('posts', [
    'title'   => 'Hello World',
    'status'  => 'active',
    'user_id' => 1,
])->run('insert');

$newId = Database::Go()->getLastInsertId();

// Update
Database::Go()->update('posts', ['status' => 'archived'])
    ->where('id', $id)->run('update');

// Delete
Database::Go()->delete('posts')->where('id', $id)->run('delete');

Filtering & Chaining

Method Description
where(col, val, op = '=') Add a WHERE clause (AND)
orWhere(col, val, op = '=') Add a WHERE clause (OR)
when(bool, callable) Apply a closure only when first arg is truthy
join(table, col1, col2, type) LEFT, INNER, RIGHT join
groupBy(string $column) GROUP BY clause
having(col, val, op) HAVING clause (after groupBy)
orderBy(col, dir = 'ASC') ORDER BY clause
limit(int $n) LIMIT clause
offset(int $n) OFFSET clause
pagination(perPage, page) Auto LIMIT + OFFSET for a given page
PHP
// Conditional where
$results = Database::Go()->select('posts')
    ->when(!empty($search), fn($db) => $db->where('title', '%' . $search . '%', 'LIKE'))
    ->when($status, fn($db) => $db->where('status', $status))
    ->orderBy('created_at', 'DESC')
    ->pagination(perPage: 10, page: $page)
    ->run('select');

// Join
$rows = Database::Go()
    ->select('posts p', 'p.id, p.title, u.username')
    ->join('users u', 'p.user_id', 'u.id', 'LEFT')
    ->where('p.status', 'active')
    ->run('select');

Raw Queries & Utilities

Method Description
rawQuery(string $sql, array $params) Execute arbitrary SQL with bound parameters
describe(string $table) DESCRIBE a table — returns column info
func(string $expr) Wrap a SQL function expression (e.g. NOW())
raw(string $expr) Insert a raw SQL fragment into a value slot
toDate(string $date) (static) Convert a date string to MySQL Y-m-d format
start() BEGIN a PDO transaction
end(bool $commit) COMMIT or ROLLBACK the active transaction
dbServer() Return the database server version string
dbName() Return the name of the connected database
PHP
// Transaction
$db = Database::Go();
$db->start();
try {
    $db->insert('orders', $orderData)->run('insert');
    $db->insert('order_items', $itemData)->run('insert');
    $db->end(true);   // commit
} catch (Throwable $e) {
    $db->end(false);  // rollback
}

// Raw query
$db->rawQuery('UPDATE settings SET value = ? WHERE key = ?', ['active', 'status']);