PHPackages                             simplecomplex/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. simplecomplex/database

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

simplecomplex/database
======================

Database abstraction for transparent MariaDB, MS SQL interaction.

3.0(5y ago)0137MITPHPPHP &gt;=7.0CI failing

Since May 3Pushed 5y ago2 watchersCompare

[ Source](https://github.com/simplecomplex/php-database)[ Packagist](https://packagist.org/packages/simplecomplex/database)[ Docs](https://github.com/simplecomplex/php-database)[ RSS](/packages/simplecomplex-database/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (5)Versions (22)Used By (0)

(PHP) Database
==============

[](#php-database)

- [Database engine specifics](#database-engine-specifics)
- [Examples - MariaDB/MySQL](#mariadb-mysql)
- [Examples - MS SQL](#ms-sql)
- [Requirements](#requirements)

Scope
-----

[](#scope)

Compact cross-engine relational database abstraction which handles common engine-specific peculiarities.

Features
--------

[](#features)

- uniform classes and methods across database engines
- *client* - *query* - *result* architecture
- chainable methods
- a database broker to keep track of all created clients
- extensive error handling/logging and defensive code style

### Client

[](#client)

- auto-reconnects, when reasonable
- safe transaction handling
- all connection options supported

### Query

[](#query)

- auto-detects parameter types when no type string (i|d|s|b) given
- ?-parameter substitution in non-prepared statements

### Result

[](#result)

- affected rows, insert ID, number of rows, number of columns
- fetch array/object, fetch all rows
- moving to next set/row

### MariaDB/MySQL features

[](#mariadbmysql-features)

- multiple selecting queries, append query
- result mode *use*; *store* only for non-prepared statement
- number of rows not supported for prepared statement (because *use*)

### MS SQL features

[](#ms-sql-features)

- automated typed arguments handling (SQLSRV\_PARAM\_IN etc.)
- automated insert ID retrieval
- result mode (SQLSRV\_CURSOR\_FORWARD etc.) defense against wrong use

Database engine specifics
-------------------------

[](#database-engine-specifics)

### MariaDB/MySQL (PHP MySQLi/mysqlnd)

[](#mariadbmysql-php-mysqlimysqlnd)

A MariaDB/MySQL **multi-query** is an SQL string containing more queries delimited by semicolon.
Every query may be a SELECT (or likewise) producing a result set.

PHP's MySQLi extension only offers native ?-parameter substitution for prepared statements, however the **`MariaDb::parameters()`** method mends that (*somewhat*); for simple statements.
Still, **go for prepared statements if security is the major concern**.

The MySQLi extension encompasses around 100 functions/methods/properties. Fairly confusing; this abstraction only utilizes a dozen or so of them.

### MS SQL (PHP Sqlsrv)

[](#ms-sql-php-sqlsrv)

PHP's Sqlsrv offers native ?-parameter substitution for simple statements as well as prepared statements.

There's no MS SQL **result mode** which supports (INSERT) affected-rows as well as (SELECT) num-rows.
So care should be taken to use 'forward' when inserting and 'static' or 'keyset' when selecting;
use **`MsSqlClient::query()`** option `(string) result_mode`.

MS SQL/Sqlsrv has no direct means for getting insert ID, but supports likewise via a 'magic' query appended to an INSERT statement.
**`MsSqlQuery`**+**`MsSqlResult`** handles the issue transparently when **`MsSqlClient::query()`** receives the option `(bool) insert_id`.

The Sqlsrv extension is a well-made tight no-nonsense API consisting of 20-odd functions.

Examples
--------

[](#examples)

### MariaDB/MySQL

[](#mariadbmysql)

```
// Get or create client via the broker -----------------------------------------
/** @var \Psr\Container\ContainerInterface $container */
$container = Dependency::container();
/** @var \SimpleComplex\Database\DatabaseBroker $db_broker */
$db_broker = $container->get('database-broker');
/** @var \SimpleComplex\Database\MariaDbClient $client */
$client = $db_broker->getClient(
    'some-client',
    'mariadb',
    [
        'host' => 'localhost',
        'database' => 'some_database',
        'user' => 'some-user',
        'pass' => '∙∙∙∙∙∙∙∙',
    ]
);

// Or create client directly ---------------------------------------------------
use SimpleComplex\Database\MariaDbClient;
$client = new MariaDbClient(
    'some-client',
    [
        'host' => 'localhost',
        'database' => 'some_database',
        'user' => 'some-user',
        'pass' => '∙∙∙∙∙∙∙∙',
    ]
);

// Insert two rows, using a prepared statement ---------------------------------
$arguments = [
    'lastName' => 'Doe',
    'firstName' => 'Jane',
    'birthday' => '1970-01-01',
];
/** @var \SimpleComplex\Database\MariaDbQuery $query */
$query = $client->query('INSERT INTO person (lastName, firstName, birthday) VALUES (?, ?, ?)')
    ->prepare('sss', $arguments)
    // Insert first row.
    ->execute();
$arguments['firstName'] = 'John';
// Insert second row.
/** @var \SimpleComplex\Database\MariaDbResult $result */
$result = $query->execute();
$affected_rows = $result->affectedRows();
$insert_id = $result->insertId();

// Get a row, using a simple statement -----------------------------------------
$somebody = $client->query('SELECT * FROM person WHERE personId > ? AND personId < ?')
    ->parameters('ii', [1, 3])
    ->execute()
    ->fetchArray();

// Get all rows, using a simple statement, and list them by 'personId' column --
$everybody = $client->query('SELECT * FROM person')
    ->execute()
    ->fetchArrayAll(DbResult::FETCH_ASSOC, 'personId');
```

### MS SQL

[](#ms-sql)

```
// Create client via the broker ------------------------------------------------
/** @var \SimpleComplex\Database\MsSqlClient $client */
$client = Dependency::container()
    ->get('database-broker')
    ->getClient(
        'some-client',
        'mssql',
        [
            'host' => 'localhost',
            'database' => 'some_database',
            'user' => 'some-user',
            'pass' => '∙∙∙∙∙∙∙∙',
        ]
    );

// Insert two rows, using a prepared statement
// and arguments that aren't declared as sqlsrv typed arrays -------------------
$arguments = [
    'lastName' => 'Doe',
    'firstName' => 'Jane',
    'birthday' => '1970-01-01',
];
/** @var \SimpleComplex\Database\MsSqlQuery $query */
$query = $client->query('INSERT INTO person (lastName, firstName, birthday) VALUES (?, ?, ?)', [
        // SQLSRV_CURSOR_FORWARD to get affected rows.
        'result_mode' => 'forward',
        // For MsSqlResult::insertId().
        'insert_id' => true,
    ])
    ->prepare('sss', $arguments)
    // Insert first row.
    ->execute();
$arguments['firstName'] = 'John';
// Insert second row.
/** @var \SimpleComplex\Database\MsSqlResult $result */
$result = $query->execute();
$affected_rows = $result->affectedRows();
$insert_id = $result->insertId();

// Insert two rows, using a prepared statement
// and types empty (guess type argument's actual type)
// and arguments partially declared as sqlsrv typed arrays ---------------------
$arguments = [
    [
        'Doe',
        SQLSRV_PARAM_IN,
        null,
        SQLSRV_SQLTYPE_VARCHAR('max')
    ],
    [
        'Jane',
    ],
    '1970-01-01',
];
$query = $client->query('INSERT INTO person (lastName, firstName, birthday) VALUES (?, ?, ?)')
    ->prepare('', $arguments)
    // Insert first row.
    ->execute();
// Insert second row.
$arguments[1][0] = 'John';
$query->execute();

// Get a row, using a simple statement -----------------------------------------
$somebody = $client->query('SELECT * FROM person WHERE personId > ? AND personId < ?')
    ->parameters('ii', [1, 3])
    ->execute()
    ->fetchArray();

// Get all rows, using a simple statement, and list them by 'personId' column --
$everybody = $client->query('SELECT * FROM person')
    ->execute()
    ->fetchArrayAll(DbResult::FETCH_ASSOC, 'personId');
```

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

[](#requirements)

- PHP &gt;=7.0
- [PSR-3 Log](https://github.com/php-fig/log)
- [SimpleComplex Utils](https://github.com/simplecomplex/php-utils)
- [SimpleComplex Validate](https://github.com/simplecomplex/php-validate)

MariaDB equires the [mysqlnd driver](https://dev.mysql.com/downloads/connector/php-mysqlnd) (PHP default since v. 5.4), or better.

### Suggestions

[](#suggestions)

- PHP MySQLi extension, if using MariaDB/MySQL database
- PHP (PECL) Sqlsrv extension, if using MS SQL database
- [SimpleComplex Inspect](https://github.com/simplecomplex/inspect) Great for logging; better variable dumps and traces.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 99.4% 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 ~49 days

Recently: every ~114 days

Total

17

Last Release

2137d ago

Major Versions

0.9.3 → 1.02018-08-12

1.x-dev → 2.02019-11-10

2.0 → 3.02020-07-08

### Community

Maintainers

![](https://www.gravatar.com/avatar/cc4dc35e0d2b8e4619ae2fe2d083cb3c64b09127ecb318c3909025fc0aae1e7f?d=identicon)[jacobfriis](/maintainers/jacobfriis)

---

Top Contributors

[![jacobfriis](https://avatars.githubusercontent.com/u/3807905?v=4)](https://github.com/jacobfriis "jacobfriis (173 commits)")[![simplecomplex](https://avatars.githubusercontent.com/u/10960036?v=4)](https://github.com/simplecomplex "simplecomplex (1 commits)")

---

Tags

databasemysqlmariadbMS SQL

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[doctrine/dbal

Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.

9.7k578.4M5.6k](/packages/doctrine-dbal)[cycle/database

DBAL, schema introspection, migration and pagination

64690.9k31](/packages/cycle-database)[tommyknocker/pdo-database-class

Framework-agnostic PHP database library with unified API for MySQL, MariaDB, PostgreSQL, SQLite, MSSQL, and Oracle. Query Builder, caching, sharding, window functions, CTEs, JSON, migrations, ActiveRecord, CLI tools, AI-powered analysis. Zero external dependencies.

845.7k](/packages/tommyknocker-pdo-database-class)[chillerlan/php-database

An extensible database wrapper and query builder.

431.2k2](/packages/chillerlan-php-database)

PHPackages © 2026

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