PHPackages                             phossa2/db - 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. phossa2/db

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

phossa2/db
==========

DB connection, management, statistics library for PHP.

2.0.0(9y ago)315[1 issues](https://github.com/phossa2/db/issues)MITPHPPHP ~5.4|~7.0

Since Aug 31Pushed 9y ago1 watchersCompare

[ Source](https://github.com/phossa2/db)[ Packagist](https://packagist.org/packages/phossa2/db)[ Docs](https://github.com/phossa2/db)[ RSS](/packages/phossa2-db/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

phossa2/db
==========

[](#phossa2db)

[![Build Status](https://camo.githubusercontent.com/038c70bceda649825472f0112b0f59b1e794085e46cd1ae3b4e59b10484856a7/68747470733a2f2f7472617669732d63692e6f72672f70686f737361322f64622e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/phossa2/db)[![Code Quality](https://camo.githubusercontent.com/53d42c0669c75f4b57d07022c3c16ad26478fb0f160bf9fc2db73fad09931bd3/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f70686f737361322f64622f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/phossa2/db/)[![Code Climate](https://camo.githubusercontent.com/0fb0a216a286d8b620efb930faf4929109b1b9b6d5a8b231b9420ab4bc2a9b99/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f70686f737361322f64622f6261646765732f6770612e737667)](https://codeclimate.com/github/phossa2/db)[![PHP 7 ready](https://camo.githubusercontent.com/2d9ece5ca2bdfd611d3e23f1f3b8e701d7d976cdf813869a35dc51a6e821528f/687474703a2f2f7068703772656164792e74696d6573706c696e7465722e63682f70686f737361322f64622f6d61737465722f62616467652e737667)](https://travis-ci.org/phossa2/db)[![HHVM](https://camo.githubusercontent.com/694f8a3c6077716fc9c6e4f450cf8d4266606a8289f8e7c0ca8a82710dc1b398/68747470733a2f2f696d672e736869656c64732e696f2f6868766d2f70686f737361322f64622e7376673f7374796c653d666c6174)](http://hhvm.h4cc.de/package/phossa2/db)[![Latest Stable Version](https://camo.githubusercontent.com/abd0ba32b7b76155d0df8773aa8a15fd86865438219177fbcca1618dfd012d31/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f767072652f70686f737361322f64622e7376673f7374796c653d666c6174)](https://packagist.org/packages/phossa2/db)[![License](https://camo.githubusercontent.com/4fc6538ded72843e26a272d300ce4c95da083ce92576e10e4fdd505d579a8125/68747470733a2f2f696d672e736869656c64732e696f2f3a6c6963656e73652d6d69742d626c75652e737667)](http://mit-license.org/)

**phossa2/db** is a PHP db connection management library which handles the interaction with db.

It requires PHP 5.4, supports PHP 7.0+ and HHVM. It is compliant with [PSR-1](http://www.php-fig.org/psr/psr-1/ "PSR-1: Basic Coding Standard"), [PSR-2](http://www.php-fig.org/psr/psr-2/ "PSR-2: Coding Style Guide"), [PSR-3](http://www.php-fig.org/psr/psr-3/ "PSR-3: Logger Interface"), [PSR-4](http://www.php-fig.org/psr/psr-4/ "PSR-4: Autoloader"), and the proposed [PSR-5](https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md "PSR-5: PHPDoc").

Features
--------

[](#features)

- Simple interface. Nothing you don't need.
- Multiple db platform/driver support, currently PDO (all PDO drivers) and Mysqli.
- Handles multiple connections through driver manager

    - Round-robin load balancing

        Multiple db connections are used in round-robin fashion and weighting factor (1-10) supported. Each connection is monitored (pinged).
    - driver tagging, so user can tag different db connection as 'reader' or 'writer' etc.
- Easy profiling, get each executed sql and its execution time.
- Secure. All SQL executed through prepare/execute in low-level drivers.

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

[](#installation)

Install via the `composer` utility.

```
composer require "phossa2/db"
```

or add the following lines to your `composer.json`

```
{
    "require": {
       "phossa2/db": "2.*"
    }
}
```

Usage
-----

[](#usage)

- Driver

    - DDL

        ```
        use Phossa2\Db\Driver\Pdo\Driver as Pdo_Driver;

        $db = new Pdo_Driver([
            'dsn' => 'mysql:dbname=test;host=127.0.0.1;charset=utf8'
        ]);

        // simple delete
        if ($db->query("DELETE FROM test WHERE id < 10")) {
            echo sprintf("%d records deleted", $db->affectedRows()) . \PHP_EOL;
        } else {
            echo $db->getError() . \PHP_EOL;
        }

        // with parameters
        if ($db->query("INSERT INTO test (val) VALUES (?)", [ 100 ])) {
            echo sprintf("last id is %d", $db->lastInsertId()) . \PHP_EOL;
        } else {
            echo $db->getError() . \PHP_EOL;
        }
        ```
    - SELECT

        ```
        // simple select
        if ($db->query("SELECT * FROM test WHERE id < 10")) {
            $rows = $db->getResult()->fetchAll();
        } else {
            echo $db->getError() . \PHP_EOL;
        }

        // fetch first 5 rows
        if ($db->query("SELECT * FROM test WHERE id > ? LIMIT ?", [10, 20])) {
            $rows = $db->getResult()->fetchRow(5);
        }

        // fetch first field
        if ($db->query("SELECT id, name FROM test WHERE id < :id", ['id' => 10])) {
            $cols = $db->getResult()->fetchCol('id');
        }
        ```
- Statment

    `Statement` is returned after `$db->prepare()`.

    ```
    // PREPARE using prepare()
    if ($db->prepare("SELECT * FROM test WHERE id < :id")) {
        $stmt = $db->getStatement();
        if ($stmt->execute(['id' => 10])) {
            $rows = $stmt->getResult()->fetchAll();
        }
    } else {
        echo $db->getError() . \PHP_EOL;
    }
    ```
- Result

    `Result` is returned by `$db->getResult()` or `$stmt->getResult()`

    ```
    if ($db->query('SELECT * FROM test')) {
        // SELECT
        if ($db->getResult()->isSelect()) {
            // get fields count
            $fieldCount = $db->getResult()->fieldCount();
            // row count
            $rowCount = $db->getResult()->rowCount();

        // DDL
        } else {
            $affectedRows = $db->getResult()->affectedRows();
        }
    }
    ```

Mysqli
------

[](#mysqli)

Mysqli driver is also supported.

```
use Phossa2\Db\Driver\Mysqli\Driver as Mysqli_Driver;

$db = new Mysqli_Driver([
    'db' => 'mysql',
    'host' => '127.0.0.1',
    'charset' => 'utf8'
]);

// simple delete
if ($db->query("DELETE FROM test WHERE id < ?", [10])) {
    echo sprintf("%d records deleted", $db->affectedRows()) . \PHP_EOL;
} else {
    echo $db->getError() . \PHP_EOL;
}
```

**Note**: named parameters are not supported in Mysqli driver.

Driver manager
--------------

[](#driver-manager)

Driver manager manages multiple db connections. Weighting factor `N` means add one driver virtually N times. Adding driver *A* with factor 5 and adding driver *B* with factor 1 into the pool, means when calling `getDriver()`, user will get *A* five times vs *B* for one time.

```
// dbwriter 1
$db1 = (new Phossa2\Db\Driver\Pdo\Driver($conf1))->addTag('RW');

// dbreader 2
$db2 = (new Phossa2\Db\Driver\Pdo\Driver($conf2))->addTag('RO');

// dbreader 3
$db3 = (new Phossa2\Db\Driver\Pdo\Driver($conf3))->addTag('RO');

// db manager
$dbm = (new Phossa2\Db\Manager\Manager())
    ->addDriver($db1, 1)    // writable connection with factor 1
    ->addDriver($db2, 5)    // read_only, factor 5
    ->addDriver($db3, 5)    // read_only, factor 5

// get a db connect, no matter writer or reader
$db = $dbm->getDriver();

// get a readonly driver
$db = $dbm->getDriver('RO');

```

SQL profiling
-------------

[](#sql-profiling)

Get the executed SQL and its execution time.

```
// init driver
$db = new Phossa2\Db\Driver\Pdo\Driver($conf);

// enable profiling
$db->enableProfiling();

// execute a DELETE
$db->query("DELETE FROM test WHERE test_id > 10");

// get sql
$sql = $db->getProfiler()->getSql();
$time = $db->getProfiler()->getExecutionTime();
```

Method overloading
------------------

[](#method-overloading)

Methods from `Phossa2\Db\Interfaces\ResultInterface` can be accessed through the db driver after successful execution of a query.

```
if ($db->query('SELECT * FROM test')) {
    // normally is $db->getResult()->fetchAll()
    $rows = $db->fetchAll();
}
```

Change log
----------

[](#change-log)

Please see [CHANGELOG](CHANGELOG.md) from more information.

Testing
-------

[](#testing)

```
$ composer test
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTE](CONTRIBUTE.md) for more information.

Dependencies
------------

[](#dependencies)

- PHP &gt;= 5.4.0
- phossa2/shared &gt;= 2.0.25

License
-------

[](#license)

[MIT License](http://mit-license.org/)

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance13

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 95.5% 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

Unknown

Total

1

Last Release

3544d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6e0ecf2ab11402101d86a36b457973b81149757a53a67dd048bbfb9025890abf?d=identicon)[phossa2](/maintainers/phossa2)

---

Top Contributors

[![phossa](https://avatars.githubusercontent.com/u/8499165?v=4)](https://github.com/phossa "phossa (21 commits)")[![phossa2](https://avatars.githubusercontent.com/u/19922046?v=4)](https://github.com/phossa2 "phossa2 (1 commits)")

---

Tags

dbphossa

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/phossa2-db/health.svg)

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

###  Alternatives

[robmorgan/phinx

Phinx makes it ridiculously easy to manage the database migrations for your PHP app.

4.5k46.2M405](/packages/robmorgan-phinx)[spatie/laravel-translation-loader

Store your language lines in the database, yaml or other sources

8362.9M51](/packages/spatie-laravel-translation-loader)[aura/sqlquery

Object-oriented query builders for MySQL, Postgres, SQLite, and SQLServer; can be used with any database connection library.

4572.9M34](/packages/aura-sqlquery)[laminas/laminas-db

Database abstraction layer, SQL abstraction, result set abstraction, and RowDataGateway and TableDataGateway implementations

13922.5M206](/packages/laminas-laminas-db)[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)[danielme85/laravel-log-to-db

Custom Laravel Log channel handler that can store log events to SQL or MongoDB databases. Uses Laravel native logging functionality.

135934.5k1](/packages/danielme85-laravel-log-to-db)

PHPackages © 2026

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