PHPackages                             v-dem/queasy-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. v-dem/queasy-db

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

v-dem/queasy-db
===============

Database access classes, part of QuEasy PHP framework

v1.3.0(7mo ago)41642[16 issues](https://github.com/v-dem/queasy-db/issues)LGPL-3.0-onlyPHPPHP &gt;=5.3.0CI passing

Since Feb 25Pushed 2mo ago2 watchersCompare

[ Source](https://github.com/v-dem/queasy-db)[ Packagist](https://packagist.org/packages/v-dem/queasy-db)[ Docs](https://github.com/v-dem/queasy-db/)[ RSS](/packages/v-dem-queasy-db/feed)WikiDiscussions master Synced today

READMEChangelog (5)Dependencies (3)Versions (7)Used By (0)

[![Codacy Badge](https://camo.githubusercontent.com/325ccdf8320a318a08443453be3b1652cc2c9b41a25c50ee484f23d21bd988ca/68747470733a2f2f6170702e636f646163792e636f6d2f70726f6a6563742f62616467652f47726164652f3934313063363937343939613433383861323638623064626663306266653739)](https://app.codacy.com/gh/v-dem/queasy-db/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade)[![Codacy Badge](https://camo.githubusercontent.com/39b288d5e0f834e36f028ee7611e06bd10fbed0052aae37ffdcd4d6ca4b06431/68747470733a2f2f6170702e636f646163792e636f6d2f70726f6a6563742f62616467652f436f7665726167652f3934313063363937343939613433383861323638623064626663306266653739)](https://app.codacy.com/gh/v-dem/queasy-db/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_coverage)[![Total Downloads](https://camo.githubusercontent.com/27a3f199f2ab4a22cfb412c832b2f3b51b272805a5642b6933fb4800f7db0a4d/68747470733a2f2f706f7365722e707567782e6f72672f762d64656d2f7175656173792d64622f646f776e6c6f616473)](https://packagist.org/packages/v-dem/queasy-db)[![Latest Stable Version](https://camo.githubusercontent.com/0b78f1f0f934702ff599176b34fe43c2b4ee37a7a9f7ce6f59f5ed4f70f999d1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f762d64656d2f7175656173792d6462)](https://packagist.org/packages/v-dem/queasy-db)[![License](https://camo.githubusercontent.com/af5da103c20ab64e9dfb5c4772237b6f5df15f8898238e973d16eb321be3065c/68747470733a2f2f706f7365722e707567782e6f72672f762d64656d2f7175656173792d64622f6c6963656e7365)](https://packagist.org/packages/v-dem/queasy-db)

[QuEasy PHP Framework](https://github.com/v-dem/queasy-framework/) - Database
=============================================================================

[](#queasy-php-framework---database)

Package `v-dem/queasy-db`
-------------------------

[](#package-v-demqueasy-db)

QuEasy DB is a set of database access classes mainly for CRUD operations. Some of the most usual queries can be built automatically (like `SELECT` by unique field, `UPDATE`, `INSERT` and `DELETE`). Complex queries can be defined in database and/or tables config. Also there's a simple query builder. The main goal is to separate `SQL` queries out of `PHP` code and provide an easy way for CRUD operations.

### Features

[](#features)

- QuEasy DB extends `PDO` class, so any project which uses `PDO` can be seamlessly moved to use QuEasy DB.
- Simple CRUD database operations in just one PHP code row.
- Simple query builder.
- Separating SQL queries from PHP code.

### Requirements

[](#requirements)

- PHP version 5.3 or higher

### Installation

[](#installation)

```
composer require v-dem/queasy-db

```

This will also install `v-dem/queasy-helper`.

### Usage

[](#usage)

#### Notes

[](#notes)

- You can use `setLogger()` method which accepts `Psr\Log\LoggerInterface` implementation to log all queries, by default `Psr\Log\NullLogger` is used.
- By default error mode (`PDO::ATTR_ERRMODE`) is set to `PDO::ERRMODE_EXCEPTION` (as in PHP8). If you need to use other error mode and are using `Db::trans()` method then be sure to manually check `errorInfo()` and throw an exception inside transaction.
- For PostgreSQL you may need to add option `Db::ATTR_USE_RETURNING => true` on initialization to make `Db::id()` work (it will add `RETURNING "id"` to each single `INSERT` statement).
- All table and column names in auto-generated SQL code are enclosed in double quotes (as per ANSI SQL standard) so check following notes:
- For MySQL need to set option `PDO::MYSQL_ATTR_INIT_COMMAND` to `SET SQL_MODE = ANSI_QUOTES` or run same query after initialization.
- For MS SQL Server need to run `SET QUOTED_IDENTIFIER ON` or `SET ANSI_DEFAULTS ON` query after initialization.

#### Initialization

[](#initialization)

```
$db = new queasy\db\Db(
    [
        'connection' => [
            'dsn' => 'pgsql:host=localhost;dbname=test',
            'user' => 'test_user',
            'password' => 'test_password',
            'options' => [
                ...options...
            ]
        ]
    ]
);
```

Or PDO-way:

```
$db = new queasy\db\Db('pgsql:host=localhost;dbname=test', 'test_user', 'test_password', $options);
```

If DSN is not set then `SQLite` in-memory database will be used:

```
$db = new queasy\db\Db();
```

- `queasy\db\Table` instances can be accessed like `$db->users`

#### Retrieving records

[](#retrieving-records)

##### Get all records from `users` table

[](#get-all-records-from-users-table)

```
$users = $db->users->all();
```

##### Using `foreach` with `users` table

[](#using-foreach-with-users-table)

```
foreach ($db->users as $user) {
    // Do something
}
```

##### Get single record from `users` table by `id` key

[](#get-single-record-from-users-table-by-id-key)

```
$user = $db->users->id[$userId];
```

It's possible to use `select()` method to pass PDO options; `select()` returns PDOStatement instance:

```
$users = $db->users->id->select($userId, $options);
```

##### Select multiple records

[](#select-multiple-records)

```
$users = $db->users->id[[$userId1, $userId2]];
```

#### Using query builder (`queasy\db\query\QueryBuidler`)

[](#using-query-builder-queasydbqueryquerybuidler)

- Method `queasy\db\Table::where()` returns `queasy\db\query\QueryBuilder` instance

##### Select records using query

[](#select-records-using-query)

```
$usersFound = $db->users->where('
    "name" LIKE :nameFilter
    AND "is_active" = 1',
    [
        'name' => $nameFilter . '%'
    ]
)->select();
```

- `QueryBuilder`'s method `select()` returns `PDOStatement`, you can use it as iterator in `foreach` loop or retrieve records using `fetch()`, `fetchAll()` etc
- `select()` method accepts `$params` array where you can use aliases or expressions:

```
$db->users
    ->where()
    ->select(['count' => $db->expr('count(*)')])
    ->fetch()['count'];
```

#### Inserting records

[](#inserting-records)

##### Insert a record into `users` table using associative array

[](#insert-a-record-into-users-table-using-associative-array)

```
$db->users[] = [
    'email' => 'john.doe@example.com',
    'password_hash' => sha1('myverystrongpassword')
];
```

##### Insert a record into `users` table by fields order

[](#insert-a-record-into-users-table-by-fields-order)

```
$db->users[] = [
    'john.doe@example.com',
    sha1('myverystrongpassword')
];
```

##### Insert many records into `users` table using associative array (it will generate single `INSERT` statement)

[](#insert-many-records-into-users-table-using-associative-array-it-will-generate-single-insert-statement)

```
$db->users[] = [
    [
        'email' => 'john.doe@example.com',
        'password_hash' => sha1('myverystrongpassword')
    ], [
        'email' => 'mary.joe@example.com',
        'password_hash' => sha1('herverystrongpassword')
    ]
];
```

##### Insert many records into `users` table by order

[](#insert-many-records-into-users-table-by-order)

```
$db->users[] = [
    [
        'john.doe@example.com',
        sha1('myverystrongpassword')
    ], [
        'mary.joe@example.com',
        sha1('herverystrongpassword')
    ]
];
```

Also it's possible to use `insert()` method (in the same way as above) when need to pass PDO options; returns last insert id for single insert and number of inserted rows for multiple inserts:

```
$userId = $db->users->insert([
    'email' => 'john.doe@example.com',
    'password_hash' => sha1('myverystrongpassword')
], $options);
```

```
$insertedRowsCount = $db->users->insert([
    [
        'email' => 'john.doe@example.com',
        'password_hash' => sha1('myverystrongpassword')
    ], [
        'email' => 'mary.joe@example.com',
        'password_hash' => sha1('herverystrongpassword')
    ]
], $options);
```

- Second argument (`$options`) is optional, it will be passed to `PDO::prepare()`

#### Updating records

[](#updating-records)

##### Update a record in `users` table by `id` key

[](#update-a-record-in-users-table-by-id-key)

```
$db->users->id[$userId] = [
    'password_hash' => sha1('mynewverystrongpassword')
]
```

```
$updatedRowsCount = $db->users->id->update($userId, [
    'password_hash' => sha1('mynewverystrongpassword')
], $options);
```

- Third argument (`$options`) is optional, it will be passed to `PDO::prepare()`

##### Update multiple records

[](#update-multiple-records)

```
$db->users->id[[$userId1, $userId2]] = [
    'is_blocked' => true
]
```

#### Deleting records

[](#deleting-records)

##### Delete a record in `users` table by `id` key

[](#delete-a-record-in-users-table-by-id-key)

```
unset($db->users->id[$userId]);
```

##### Delete multiple records

[](#delete-multiple-records)

```
unset($db->users->id[[$userId1, $userId2]]);
```

```
$deletedRowsCount = $db->users->id->delete([[$userId1, $userId2]], $options);
```

- Second argument (`$options`) is optional, it will be passed to `PDO::prepare()`

#### Other functions

[](#other-functions)

##### Get last insert id (alias for `lastInsertId()` method)

[](#get-last-insert-id-alias-for-lastinsertid-method)

```
$newUserId = $db->id();
```

##### Get count of all records in `users` table

[](#get-count-of-all-records-in-users-table)

```
$usersCount = count($db->users);
```

##### Using transactions

[](#using-transactions)

```
$db->trans(function() use($db) {
    // Run queries inside a transaction, for example:
    $db->users[] = [
        'john.doe@example.com',
        sha1('myverystrongpassword')
    ];
});
```

- On exception transaction is rolled back and exception re-thrown to outer code.

##### Run custom queries (returns `PDOStatement`)

[](#run-custom-queries-returns-pdostatement)

```
$users = $db->run('
    SELECT  *
    FROM    "users"
    WHERE   "name" LIKE concat(\'%\', :searchName, \'%\')',
    [
        ':searchName' => 'John'
    ],
    $options
)->fetchAll();
```

- Third argument (`$options`) is optional, it will be passed to `PDO::prepare()`

##### Run query predefined in configuration

[](#run-query-predefined-in-configuration)

This feature can help keep code cleaner and place SQL code outside PHP, somewhere in config files.

```
$db = new queasy\db\Db(
    [
        'connection' => [
            'dsn' => 'pgsql:host=localhost;dbname=test',
            'user' => 'test_user',
            'password' => 'test_password'
        ],
        'queries' => [
            'searchUsersByName' => [
                'sql' => '
                    SELECT  *
                    FROM    "users"
                    WHERE   "name" LIKE concat(\'%\', :searchName, \'%\')',
                'returns' => Db::RETURN_ALL
            ]
        ]
    ]
);

$users = $db->searchUsersByName([
    'searchName' => 'John'
]);
```

- Possible values for `returns` option are `Db::RETURN_STATEMENT` (default, returns `PDOStatement` instance), `Db::RETURN_ONE`, `Db::RETURN_ALL` (using `PDOStatement::fetchAll()` method), `Db::RETURN_VALUE`

Also it is possible to group predefined queries by tables:

```
$db = new queasy\db\Db(
    [
        'connection' => [
            'dsn' => 'pgsql:host=localhost;dbname=test',
            'user' => 'test_user',
            'password' => 'test_password'
        ],
        'tables' => [
            'users' => [
                'searchByName' => [
                    'sql' => '
                        SELECT  *
                        FROM    "user_roles"
                        WHERE   "name" LIKE concat(\'%\', :searchName, \'%\')',
                    'returns' => Db::RETURN_ALL
                ]
            ]
        ]
    ]
);

$users = $db->users->searchByName([
    'searchName' => 'John'
]);
```

##### Using `v-dem/queasy-db` together with `v-dem/queasy-config` and `v-dem/queasy-log`

[](#using-v-demqueasy-db-together-with-v-demqueasy-config-and-v-demqueasy-log)

`config.php:`

```
return [
    'db' => [
        'connection' => [
            'dsn' => 'pgsql:host=localhost;dbname=test',
            'user' => 'test_user',
            'password' => 'test_password'
        ],
        'tables' => [
            'users' => [
                'searchByName' => [
                    'sql' => '
                        SELECT  *
                        FROM    "users"
                        WHERE   "name" LIKE concat(\'%\', :searchName, \'%\')',
                    'returns' => Db::RETURN_ALL
                ]
            ]
        ]
    ],

    'logger' => [
        [
            'class' => queasy\log\ConsoleLogger::class,
            'minLevel' => Psr\Log\LogLevel::DEBUG
        ]
    ]
];
```

Initializing:

```
$config = new queasy\config\Config('config.php'); // Can be also INI, JSON or XML

$logger = new queasy\log\Logger($config->logger);

$db = new queasy\db\Db($config->db);
$db->setLogger($logger);

$users = $db->users->searchByName([
    'searchName' => 'John'
]);
```

- All queries will be logged with `Psr\Log\LogLevel::DEBUG` level. Also it's possible to use any other logger class compatible with PSR-3.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance56

Moderate activity, may be stable

Popularity16

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 99.3% 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 ~118 days

Recently: every ~99 days

Total

6

Last Release

215d ago

PHP version history (2 changes)1.0.0PHP &gt;=5.3.0|&gt;=7.0.0|&gt;=8.0.0

1.1.0PHP &gt;=5.3.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1413537?v=4)[Virginia Department of Emergency Management](/maintainers/vdem)[@vdem](https://github.com/vdem)

---

Top Contributors

[![v-dem](https://avatars.githubusercontent.com/u/6298430?v=4)](https://github.com/v-dem "v-dem (296 commits)")[![codacy-badger](https://avatars.githubusercontent.com/u/23704769?v=4)](https://github.com/codacy-badger "codacy-badger (1 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")

---

Tags

cruddatabasemysqlpdopdo-wrapperphppostgresqlsqlitesqlite3wrapperdatabasemysqlsqlitepostgresqlpdocrudpdo-wrapper

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/v-dem-queasy-db/health.svg)

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

###  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)[ezsql/ezsql

Advance database access library. Make interacting with a database ridiculously easy. An universal interchangeable CRUD system.

86946.7k](/packages/ezsql-ezsql)[jv2222/ezsql

Advance database access library. Make interacting with a database ridiculously easy. An universal interchangeable CRUD system.

87311.3k2](/packages/jv2222-ezsql)[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)[delight-im/db

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

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

PHPackages © 2026

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