PHPackages                             solophp/database - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. solophp/database

ActiveLibrary[Database &amp; ORM](/categories/database)

solophp/database
================

Lightweight and flexible PHP database wrapper with support for multiple database types, query building, and optional logging.

v2.10.0(1y ago)0146MITPHPPHP &gt;=8.2

Since Sep 3Pushed 6mo ago1 watchersCompare

[ Source](https://github.com/SoloPHP/Database)[ Packagist](https://packagist.org/packages/solophp/database)[ RSS](/packages/solophp-database/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (1)Versions (27)Used By (0)

Solo Database
=============

[](#solo-database)

[![Version](https://camo.githubusercontent.com/8801d735f11bc0ace95751fd5bb5d9bb104a51c331376cc15dd63ea4ace82c77/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d322e31302e302d626c75652e737667)](https://github.com/solophp/database)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](https://opensource.org/licenses/MIT)

Lightweight and flexible PHP database wrapper with support for multiple database types, query building, and optional logging.

Installation
------------

[](#installation)

```
composer require solophp/database
```

Features
--------

[](#features)

- Support for MySQL, PostgreSQL, SQLite, SQL Server, and other PDO-compatible databases
- Safe query building with type-specific placeholders
- Flexible null value support, including for date parameters
- Configurable fetch modes (arrays or objects)
- Query preparation without execution
- Optional table prefixing
- Integration with PSR-3 compatible Solo Logger
- Transaction support
- Clean and flexible API with method chaining

Requirements
------------

[](#requirements)

- PHP 8.2+
- PDO extension
- Solo Logger ^1.0

API Reference
-------------

[](#api-reference)

MethodArgumentsDescriptionReturn Type`query()``string $sql, mixed ...$params`Execute a query with placeholders`self``prepare()``string $sql, mixed ...$params`Prepare SQL string without execution`string``fetchAll()``?int $fetchMode = null`Fetch all rows`array&lt;int`fetch()``?int $fetchMode = null`Fetch single row`array`fetchColumn()``int $columnIndex = 0`Fetch single column from next row`mixed``lastInsertId()`—Get last inserted ID`string`rowCount()`—Get number of affected rows`int``beginTransaction()`—Begin transaction`void``commit()`—Commit transaction`void``rollBack()`—Roll back transaction`void``inTransaction()`—Check if in transaction`bool``withTransaction()``callable $callback`Run logic inside a safe transaction (auto rollback on exception)`mixed`Query Placeholders
------------------

[](#query-placeholders)

PlaceholderDescription`?s`String (safely quoted)`?i`Integer`?f`Float`?a`Array (for IN statements)`?A`Associative Array (for SET statements)`?t`Table name (with prefix)`?c`Column name (safely quoted)`?d`Date (DateTimeImmutable or null)`?l`LIKE condition with wildcards`?M`Multi-row INSERT (array of arrays)`?r`Raw parameter (unescaped)Usage
-----

[](#usage)

### Basic Configuration

[](#basic-configuration)

```
use Solo\Database\{Config, Connection};
use Solo\Logger;
use PDO;

$config = new Config(
    hostname: 'localhost',
    username: 'user',
    password: 'pass',
    dbname: 'mydb',
    prefix: 'prefix_',
    fetchMode: PDO::FETCH_OBJ
);

$logger = new Logger('/path/to/logs/db.log');
$connection = new Connection($config, $logger);
$db = new Database($connection);
```

### Query Examples

[](#query-examples)

```
// Basic SELECT
$users = $db->query("SELECT * FROM ?t", 'users')->fetchAll();

// INSERT with associative array
$userData = [
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'age' => 25,
    'created_at' => new DateTimeImmutable()
];
$db->query("INSERT INTO ?t SET ?A", 'users', $userData);

// INSERT multiple rows
$data = [['John', 30], ['Alice', 25]];
$db->query("INSERT INTO ?t (name, age) VALUES ?M", 'users', $data);

// Handling null values
$userData = [
    'name' => 'Jane Doe',
    'created_at' => new DateTimeImmutable(),
    'updated_at' => null,
];
$db->query("INSERT INTO ?t SET ?A", 'users', $userData);

// Fetch single row
$user = $db->query("SELECT * FROM ?t WHERE id = ?i", 'users', 1)->fetch();

// Override fetch mode
$userArray = $db->query("SELECT * FROM ?t WHERE id = ?i", 'users', 1)->fetch(PDO::FETCH_ASSOC);

// IN clause
$ids = [1, 2, 3];
$result = $db->query("SELECT * FROM ?t WHERE id IN ?a", 'users', $ids)->fetchAll();

// Dynamic column
$column = 'email';
$userEmail = $db->query("SELECT ?c FROM ?t WHERE id = ?i", $column, 'users', 1)->fetchColumn();

// Transaction (classic)
try {
    $db->beginTransaction();

    $db->query("INSERT INTO ?t SET ?A", 'orders', ['product' => 'Laptop']);
    $db->query("UPDATE ?t SET balance = balance - ?f WHERE id = ?i", 'accounts', 799.99, 1);

    $db->commit();
} catch (Exception $e) {
    if ($db->inTransaction()) {
    $db->rollBack();
    }
    throw $e;
}

// Transaction (preferred)
$db->withTransaction(function () use ($db) {
    $db->query("INSERT INTO ?t SET ?A", 'orders', ['product' => 'Laptop']);
    $db->query("UPDATE ?t SET balance = balance - ?f WHERE id = ?i", 'accounts', 799.99, 1);
});

// Prepare only
$sql = $db->prepare("SELECT * FROM ?t WHERE user_id = ?i AND status = ?s", 'orders', 15, 'pending');

// Fetch column
$email = $db->query("SELECT email FROM ?t WHERE id = ?i", 'users', 1)->fetchColumn();

// Raw expressions
use Solo\Database\Expressions\RawExpression;
$db->query("UPDATE ?t SET ?A WHERE id = ?i", 'orders', [
    'number' => new RawExpression("CONCAT(RIGHT(phone, 4), '-', id)")
], 42);
```

Database Support
----------------

[](#database-support)

Date formatting is handled automatically per driver:

- PostgreSQL: `Y-m-d H:i:s.u P`
- MySQL: `Y-m-d H:i:s`
- SQLite: `Y-m-d H:i:s`
- SQL Server: `Y-m-d H:i:s.u`
- DBLIB: `Y-m-d H:i:s`
- CUBRID: `Y-m-d H:i:s`

Return Types
------------

[](#return-types)

MethodDescriptionReturn Type`fetchAll(?int $fetchMode = null)`Get all rows`array&lt;int`fetch(?int $fetchMode = null)`Get one row`array`fetchColumn(int $columnIndex = 0)`Get column from next row`mixed``rowCount()`Affected rows from last query`int``lastInsertId()`Last inserted auto-increment ID`stringError Handling
--------------

[](#error-handling)

- All database operations are wrapped in try-catch blocks
- Exceptions are thrown with meaningful messages
- Logging is automatic when PSR-3 logger is configured
- Transactions via `withTransaction()` auto-rollback on failure

License
-------

[](#license)

MIT License. See LICENSE file for details.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance57

Moderate activity, may be stable

Popularity10

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~8 days

Recently: every ~14 days

Total

26

Last Release

410d ago

Major Versions

v1.4.2 → v2.0.02024-12-02

PHP version history (3 changes)v1.0.0PHP &gt;=7.4

v2.0.0PHP &gt;=8.1

v2.2.0PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/2f29817cec408d033cd4441c8f760e3ae40248dc0f66856a09080d282aee6959?d=identicon)[Vitaliy Olos](/maintainers/Vitaliy%20Olos)

---

Top Contributors

[![SoloPHP](https://avatars.githubusercontent.com/u/175482616?v=4)](https://github.com/SoloPHP "SoloPHP (36 commits)")

---

Tags

phpdatabasedbalpdo

### Embed Badge

![Health badge](/badges/solophp-database/health.svg)

```
[![Health](https://phpackages.com/badges/solophp-database/health.svg)](https://phpackages.com/packages/solophp-database)
```

###  Alternatives

[envms/fluentpdo

FluentPDO is a quick and light PHP library for rapid query building. It features a smart join builder, which automatically creates table joins.

925511.7k13](/packages/envms-fluentpdo)[lichtner/fluentpdo

FluentPDO is a quick and light PHP library for rapid query building. It features a smart join builder, which automatically creates table joins.

921274.8k6](/packages/lichtner-fluentpdo)[clouddueling/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

1.3k22.9k](/packages/clouddueling-mysqldump-php)[popphp/pop-db

Pop Db Component for Pop PHP Framework

1814.6k11](/packages/popphp-pop-db)[riverside/php-orm

PHP ORM micro-library and query builder

111.2k](/packages/riverside-php-orm)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
