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

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

finesse/mini-db
===============

Light database abstraction with a query builder

v0.7.4(7y ago)31.4k11MITPHPPHP &gt;=7.0CI failing

Since Nov 4Pushed 6y ago1 watchersCompare

[ Source](https://github.com/Finesse/MiniDB)[ Packagist](https://packagist.org/packages/finesse/mini-db)[ Docs](https://github.com/Finesse/MiniDB)[ RSS](/packages/finesse-mini-db/feed)WikiDiscussions master Synced 2w ago

READMEChangelog (10)Dependencies (4)Versions (14)Used By (1)

MiniDB
======

[](#minidb)

[![Latest Stable Version](https://camo.githubusercontent.com/fd1d53fd55b29e3eebfe5a2087697dd1e0b0b44da36508ed0d54b8cf99f71fd3/68747470733a2f2f706f7365722e707567782e6f72672f66696e657373652f6d696e692d64622f762f737461626c65)](https://packagist.org/packages/finesse/mini-db)[![Total Downloads](https://camo.githubusercontent.com/c076862a9c5438dc40b2291248d44f2960012a8f7b9f5741618b9e4dd019d3a0/68747470733a2f2f706f7365722e707567782e6f72672f66696e657373652f6d696e692d64622f646f776e6c6f616473)](https://packagist.org/packages/finesse/mini-db)[![PHP from Packagist](https://camo.githubusercontent.com/d35d4ae761c30637cbe066b6358f9b7157bf53dacac4e78f3f1932c41cb33985/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f66696e657373652f6d696e692d64622e737667)](https://camo.githubusercontent.com/d35d4ae761c30637cbe066b6358f9b7157bf53dacac4e78f3f1932c41cb33985/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f66696e657373652f6d696e692d64622e737667)[![Test Status](https://github.com/finesse/MiniDB/workflows/Test/badge.svg)](https://github.com/Finesse/MiniDB/actions?workflow=Test)[![Maintainability](https://camo.githubusercontent.com/c138507640c4adf070ee2e95d51afe1c8dd1ac87ee3def0ee5590621eaed8f36/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f66303662616636653864363838623238636431322f6d61696e7461696e6162696c697479)](https://codeclimate.com/github/Finesse/MiniDB/maintainability)[![Test Coverage](https://camo.githubusercontent.com/4d67a399eb5c488c043ef2cbc8912c33511255df362e71597fd886decdf0dd91/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f66303662616636653864363838623238636431322f746573745f636f766572616765)](https://codeclimate.com/github/Finesse/MiniDB/test_coverage)

Lightweight database abstraction in which rows are simple arrays. It has both a query builder for convenient fluent syntax and an interface for performing pure SQL queries.

```
$database = Database::create([
    'driver'   => 'mysql',
    'dsn'      => 'mysql:host=localhost;dbname=my_database',
    'username' => 'root',
    'password' => 'qwerty',
    'prefix'   => 'test_'
]);

$database->statement('
    CREATE TABLE '.$database->addTablePrefix('users').' (
        id INT(11) NOT NULL AUTO_INCREMENT,
        email VARCHAR(50) NOT NULL,
        account INT(11) NOT NULL DEFAULT 0
    )
');

$database->table('users')->insert([
    ['name' => 'Jack', 'account' => 1200],
    ['name' => 'Bob', 'account' => 500],
    ['name' => 'Richard', 'account' => 800]
]);

$database->table('users')->where('account', '>', 600)->get(); // Jack and Richard
```

Key features:

- Light with a small number of light dependencies.
- Extensible. Examples will come soon.
- The [query builder](https://github.com/Finesse/QueryScribe) and the [database connector](https://github.com/Finesse/MicroDB) can be used separately.
- Supports table prefixes.
- No static facades. Explicit delivery using dependency injection.
- Exceptions on errors.

Supported DBMSs:

- MySQL
- SQLite
- Maybe any other, didn't test it

If you need a new database system support please implement it [there](https://github.com/Finesse/MicroDB) and [there](https://github.com/Finesse/QueryScribe) using pull requests.

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

[](#installation)

You need [Composer](https://getcomposer.org) to use this library. Run in a console:

```
composer require finesse/mini-db
```

Reference
---------

[](#reference)

### Getting started

[](#getting-started)

You need to make a `Database` instance once:

```
use Finesse\MiniDB\Database;

$database = Database::create([
    'driver'   => 'mysql',                     // DBMS type: 'mysql', 'sqlite' or anything else for other (optional)
    'dsn'      => 'mysql:host=host;dbname=db', // PDO data source name (DSN)
    'username' => 'root',                      // Database username (optional)
    'password' => 'qwerty',                    // Database password (optional)
    'options'  => [],                          // PDO options (optional)
    'prefix'   => ''                           // Tables prefix (optional)
]);
```

See more about the PDO options at the [PDO constructor reference](http://php.net/manual/en/pdo.construct.php).

Alternatively you can create all the dependencies manually:

```
use Finesse\MicroDB\Connection;
use Finesse\MiniDB\Database;
use Finesse\QueryScribe\Grammars\MySQLGrammar;
use Finesse\QueryScribe\PostProcessors\TablePrefixer;

$connection = Connection::create('mysql:host=host;dbname=db', 'username', 'password');
$grammar = new MySQLGrammar();
$tablePrefixer = new TablePrefixer('demo_');

$database = new Database($connection, $grammar, $tablePrefixer);
```

### Raw SQL queries

[](#raw-sql-queries)

```
$database->insertGetId('INSERT INTO users (name, email) VALUES (?, ?), (?, ?)', ['Ann', 'ann@gmail.com', 'Bob', 'bob@rambler.com']); // 19 (the last inserted row id)

$database->select('SELECT * FROM users WHERE name = ? OR email = ?', ['Jack', 'jack@example.com']);
/*
    [
        ['id' => 4, 'name' => 'Jack', 'email' => 'demon@mail.com', 'account' => 1230],
        ['id' => 17, 'name' => 'Bill', 'email' => 'jack@example.com', 'account' => -100]
    ]
 */

$database->import('path/to/file.sql');
```

The cell values are returned as they are returned by the underlying database connection. They are not casted automatically because casting can cause a data loss.

Table prefix is not applied in raw queries. Use `$database->addTablePrefix()` to apply it.

```
$database->select('SELECT * FROM '.$database->addTablePrefix('users').' ORDER BY id');
```

Be careful, the `statements` and the `import` methods don't throw an exception if the second or a next statement of the query has an error. This is [a PDO bug](https://stackoverflow.com/a/28867491/1118709).

You can find more information and examples of raw queries [there](https://github.com/Finesse/MicroDB#reference).

### Query builder

[](#query-builder)

Basic examples are presented here. You can find more cool examples [there](https://queryscribe.readthedocs.io/en/stable/building-queries/).

Values given to the query builder are treated safely to prevent SQL injections so you don't need to escape them.

#### Select

[](#select)

Many rows:

```
$database
    ->table('users')
    ->where('status', 'active')
    ->orderBy('name')
    ->offset(40)
    ->limit(10)
    ->get();

/*
    [
        ['id' => 17, 'name' => 'Bill', 'email' => 'jack@example.com', 'status' => 'active'],
        ['id' => 4, 'name' => 'Jack', 'email' => 'demon@mail.com', 'status' => 'active']
    ]
 */
```

One row:

```
$database
    ->table('users')
    ->where('status', 'active')
    ->orderBy('name')
    ->first();

/*
    ['id' => 17, 'name' => 'Bill', 'email' => 'jack@example.com', 'status' => 'active'] or null
 */
```

##### Pagination

[](#pagination)

We suggest [Pagerfanta](https://github.com/whiteoctober/Pagerfanta) to make a pagination easily.

First install Pagerfanta using [composer](https://getcomposer.org) by running in a console:

```
composer require pagerfanta/pagerfanta
```

Then make a query from which the rows should be taken:

```
$query = $database
    ->table('posts')
    ->where('category', 'archive')
    ->orderBy('date', 'desc');
    // Don't call ->get() here
```

And use Pagerfanta:

```
use Finesse\MiniDB\ThirdParty\PagerfantaAdapter;
use Pagerfanta\Pagerfanta;

$paginator = new Pagerfanta(new PagerfantaAdapter($query));
$paginator->setMaxPerPage(10); // The number of rows on a page
$paginator->setCurrentPage(3); // The current page number

$currentPageRows = $paginator->getCurrentPageResults(); // The rows for the current page
$pagesCount = $paginator->getNbPages();                 // Total pages count
$haveToPaginate = $paginator->haveToPaginate();         // Whether the number of results is higher than the max per page
```

You can find more reference and examples for Pagerfanta [there](https://github.com/whiteoctober/Pagerfanta#usage).

##### Chunking rows

[](#chunking-rows)

If you need to process a large amount of rows you can use chunking. In this approach portions of rows are fetched from the database instead of fetching all the rows at once.

```
$database
    ->table('users')
    ->orderBy('id')
    ->chunk(100, function ($users) {
        foreach ($users as $user) {
            // Process a row here
        }
    });
```

#### Aggregates

[](#aggregates)

```
$database
    ->table('products')
    ->where('price', '>', 1000)
    ->count(); // 31
```

Other aggregate methods: `avg(column)`, `sum(column)`, `min(column)` and `max(column)`.

#### Insert

[](#insert)

Many rows:

```
$database->table('debts')->insert([
    ['name' => 'Sparrow', 'amount' => 13000, 'message' => 'Sneaky guy'],
    ['name' => 'Barbos', 'amount' => 4999, 'message' => null],
    ['name' => 'Pillower', 'message' => 'Call tomorrow']
]); // 3 (number of inserted rows)
```

The string array keys are the columns names.

One row:

```
$database->table('debts')->insertGetId([
    'name' => 'Bigbigger',
    'amount' => -3500,
    'message' => 'I owe him'
]); // 4 (id of the inserted row)
```

From a select query:

```
$database->table('debts')->insertFromSelect(['name', 'amount', 'message'], function ($query) {
    $query
        ->from('users')
        ->addSelect(['name', $query->raw('- account'), 'description'])
        ->where('status', 'debtor');
}); // 6 (number of inserted rows)
```

#### Update

[](#update)

```
$database
    ->table('posts')
    ->where('date', ' 10');
// or
$query->whereRaw('MIN('.$query->quoteCompositeIdentifier('data"base.ta"ble').') > 10'); // MIN("data""base"."ta""ble") > 10
```

The above methods are also available in a `Database` object.

Make all the column names in the query have explicit table name or alias:

```
$database
    ->table('users', 'u')
    ->addSelect('name')
    ->where('status', 'verified')
    ->orWhere('u.type', 'admin')
    ->addTablesToColumnNames();

// SELECT "name" FROM "users" AS "u" WHERE "status" = ? OR "u"."type" = ?

```

Versions compatibility
----------------------

[](#versions-compatibility)

The project follows the [Semantic Versioning](http://semver.org).

License
-------

[](#license)

MIT. See [the LICENSE](LICENSE) file for details.

###  Health Score

29

—

LowBetter than 57% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity19

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 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 ~39 days

Recently: every ~23 days

Total

13

Last Release

2738d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/9006227?v=4)[Sergey M.](/maintainers/Finesse)[@Finesse](https://github.com/Finesse)

---

Top Contributors

[![Finesse](https://avatars.githubusercontent.com/u/9006227?v=4)](https://github.com/Finesse "Finesse (55 commits)")

---

Tags

databaselibrarymysqlpdoquery-buildersqlsqlitedatabasemysqlsqlitesqlpdoquery builder

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[doctrine/dbal

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

9.7k614.3M7.3k](/packages/doctrine-dbal)[cycle/database

DBAL, schema introspection, migration and pagination

71811.3k67](/packages/cycle-database)[opis/database

A database abstraction layer over PDO, that provides a powerful and intuitive query builder, bundled with an easy to use schema builder

10285.8k3](/packages/opis-database)[delight-im/db

Safe and convenient SQL database access in a driver-agnostic way

46181.6k7](/packages/delight-im-db)

PHPackages © 2026

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