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

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

phpixie/database
================

PHPixie Database library

3.11.1(6y ago)1123.6k9[1 PRs](https://github.com/PHPixie/Database/pulls)4BSD-3-ClausePHP

Since Apr 22Pushed 6y ago2 watchersCompare

[ Source](https://github.com/PHPixie/Database)[ Packagist](https://packagist.org/packages/phpixie/database)[ Docs](http://phpixie.com)[ RSS](/packages/phpixie-database/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (3)Versions (24)Used By (4)

PHPixie Database
================

[](#phpixie-database)

Supports a common query interface for MySQL, PostgreSQL, SQLite and MongoDB

[![Build Status](https://camo.githubusercontent.com/5bbcabdf2c9c2fbf258fe39f0574de45c813e1f6b1d6e4351165ff9b1d510983/68747470733a2f2f7472617669732d63692e6f72672f504850697869652f44617461626173652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/PHPixie/Database)[![Test Coverage](https://camo.githubusercontent.com/5b868e7092b35760e95c1595851c1562fabdfb3a98b2664cf07de12bd6b58355/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f504850697869652f44617461626173652f6261646765732f636f7665726167652e737667)](https://codeclimate.com/github/PHPixie/Database)[![Code Climate](https://camo.githubusercontent.com/9e416d820fdea43bf15522a9c2590f1e8e70bf8aed51f4ca8385e9e7aacd5340/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f504850697869652f44617461626173652f6261646765732f6770612e737667)](https://codeclimate.com/github/PHPixie/Database)[![HHVM Status](https://camo.githubusercontent.com/7380adfe41acf51c9e7b06fd8a8c14750b308fdd11abe049096f80cae8472776/68747470733a2f2f696d672e736869656c64732e696f2f6868766d2f706870697869652f64617461626173652e7376673f7374796c653d666c61742d737175617265)](http://hhvm.h4cc.de/package/phpixie/database)

[![Author](https://camo.githubusercontent.com/24a0a94bb83eb81ba03c32074967dc730174cfd2849e984169db461d955cdbb9/687474703a2f2f696d672e736869656c64732e696f2f62616467652f617574686f722d40647261636f6e792d626c75652e7376673f7374796c653d666c61742d737175617265)](https://twitter.com/dracony)[![Source Code](https://camo.githubusercontent.com/b93f9fc898a3cd34ddd8e422799e45f114c49fa08f60ac25b13a64595e03ed24/687474703a2f2f696d672e736869656c64732e696f2f62616467652f736f757263652d706870697869652f64617461626173652d626c75652e7376673f7374796c653d666c61742d737175617265)](https://github.com/phpixie/database)[![Software License](https://camo.githubusercontent.com/b60331a2084501dc07cf6d6964c0da58dd005d89c45cf3b28b4b22b60f5ec00f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4253442d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/phpixie/database/blob/master/LICENSE)[![Total Downloads](https://camo.githubusercontent.com/7d749f6bff8a1d3c0a16bb2a5e85ff86369f26e87e63c4364aab19269e59f9fd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f706870697869652f64617461626173652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/phpixie/database)

- [PHPixie Database](#phpixie-database)
    - [Initializing](#initializing)
    - [Querying](#querying)
        - [Operators](#operators)
        - [Tables, Subqueries and JOINs](#tables-subqueries-and-joins)
        - [Aggregation](#aggregation)
        - [Other types of queries](#other-types-of-queries)
        - [Placeholders](#placeholders)
    - [Transactions](#transactions)
    - [MongoDB](#mongodb)

Initializing
------------

[](#initializing)

```
$slice = new \PHPixie\Slice();
$database = new \PHPixie\Database($slice->arrayData(array(
    'default' => array(
        'driver' => 'pdo',
        'connection' => 'sqlite::memory:'
    )
)));
```

> If you are using the PHPixie Framework the Database component is automatically initalized for you. Access it via `$frameworkBuilder->components()->database()` and configure in the `/config/database.php` file.

```
return array(
    //You can define multiple connections
    //each with a different name
    'default' => array(
        'driver'     => 'pdo',

        //MySQL
        'connection' => 'mysql:host=localhost;dbname=phpixie',

        //or SQLite
        'connection' => 'sqlite:/some/file',

        //or Postgres
        'connection' => 'pgsql:dbname=exampledb',

        'user'       => 'root',
        'password'   => 'password'
    ),

    'other' => array(
        //connecting to MongoDD
        'driver'   => 'mongo',
        'database' => 'phpixie',
        'user'     => 'pixie',
        'password' => 'password'
    )
);
```

Querying
--------

[](#querying)

Querying relational database and MongoDB collections is very similar in PHPixie. Let's look at relational databases first

```
$connection = $database->get('default');

// SELECT * FROM `posts` WHERE `status`='published'
// LIMIT 5 OFFSET 1
$query = $connection->selectQuery();
$posts = $query
    ->table('posts')
    ->where('status', 'Published')
    ->limit(5)
    ->offset(1)
    ->execute();

// Specifying fields
$query->fields(array('id'));

// You can remove limit, offset
// specified fields, etc from the query
// using clearSomething()
$query->clearFields();

//And get it using getSomething()
$query->getFields();

//Using OR and XOR logic
$query
    ->where('status', 'published')
    ->orWhereNot('status', 'deleted')
    ->xorWhere('id', 5);

//Shorthand functions
$query
    ->and('status', 'published')
    ->orNot('status', 'deleted')
    ->xor('id', 5);

// WHERE `status` = 'published'
// OR NOT (`id` = 4 AND `views` = 5)
$query
    ->where('status', 'published')
    ->startOrNotGroup()
        ->where('id', 4)
        ->and('views', 4)
    ->endGroup();

// Less verbose syntax
$query
    ->where('status', 'published')
    ->or(function(query) {
        $query
            ->where('id', 4)
            ->and('views', 4);
    });

// More verbose syntax
// Useful for programmatic filters
$query
    ->addOperatorCondition(
        $logic    = 'and',
        $negate   = false,
        $field    = 'status',
        $operator = '=',
        array('published')
    )
    ->startConditionGroup(
        $logic    = 'and',
        $negate   = false
    );
```

> Using `and`, `or` and `xor` add conditions to the last used conditon type. So calling `or` after `where()` will be same as `orWhere()`, while using it after `having()` will be considered as `orHaving()`.

### Operators

[](#operators)

```
// So far we only compared fields with values
// But there are other operators available

// >, < , >=, where('views', '>', 5);

// comparies fields to other fields
// can be done by adding an '*'
$query->where('votes', '>=*', 'votesRequired');

// Between
$query->where('votes', 'between', 5, 6);

// In
$query->where('votes', 'in', array(5, 6));

// Like
$query->where('name', 'like', 'Welcome%');

// Regexp
$query->where('name', 'regexp', '.*');

// SQL expression
$expression = $database->sqlExpression('LOWER(?)', array('text'));
$query->where('title', $expression);

// You can also use it for fields
// SELECT COUNT(1) as `count`
$expression = $database->sqlExpression('COUNT(1)');
$query->fields(array(
    'count' => $expression
));
```

### Tables, Subqueries and JOINs

[](#tables-subqueries-and-joins)

```
// When specofying a table
// you can also define an alias for it
$query->table('posts', 'p');

// INNER JOIN `categories`
$query->join('categories')

// LEFT JOIN `categories` AS `c`
$query->join('categories', 'c', 'left')

$query
    ->on('p.categoryId', 'c.categoryId');

// The on() conditions can be used in
// the same way as where(), and apply
// to the last join() statement
$query
    ->join('categories', 'c', 'left')
        ->on('p.categoryId', 'c.id')
        ->or('p.parentCategoryId', 'c.id')
    ->join('authors')
        ->on('p.authorId', 'authors.id');

// You can use subqueries as tables,
// but you must supply the alias parameter

$query->join($subqeury, 'c', 'left')

//UNIONs
$query->union($subquery, $all = true);
```

### Aggregation

[](#aggregation)

After you define you fields you cn use `HAVING` in the same way you would use `WHERE`;

```
$query
    ->fields(array(
        'count' => $database->sqlExpression('COUNT(1)');
    ))
    ->having('count', '>', 5)
    ->or('count', 'deleteQuery()
    ->where('id', 5)
    ->execute();

// Count query is a shorthand that returns the count
// of matched items
$count = $connection->countQuery()
    ->where('id', '>', 5)
    ->execute();

// Inserting
$insertQuery = $connection->insertQuery();
$insertQuery->data(array(
    'id'    => 1,
    'title' => 'Hello'
))->execute();

// Insert multiple rows
$insertQuery->batchData(
    array('id', 'title'),
    array(
        array(1, 'Hello'),
        array(2, 'World'),
    )
)->execute();

// Getting insert id
$connection->insertId();

// Updating
$updateQuery = $connection->updateQuery();
$updateQuery
    ->set('name', 'Hello')
    ->where('id', 4)
    ->execute();

// increment values
$updateQuery
    ->increment(array(
        'views' => 1
    ))
    ->execute();
```

### Placeholders

[](#placeholders)

Query placeholders are another way to ease programmatic query building. You can create a placeholder and then later replace it with actual conditions. Here is an example:

```
$query
    ->where('status', 'published')
    ->startOrGroup();

// Add placeholder inside the OR goup
$placeholder = $query->addPlaceholder(
    $logic  = 'and',
    $negate = false,
    $allowEmpty = false
);

$query
        ->and('views', '>', 5);
    ->endGroup();

// so far this results in
// WHERE `status` = 'published'
// OR ( AND `views` > 5)

// Now we can replace the placeholder by
// adding conditions to it
$placeholder->where('votes', '>', 5);
```

Transactions
------------

[](#transactions)

The basic usage for transactions is to rollback them if an exception occured and then rethrow the exception

```
$database->beginTransaction();
// ...
try {
    // ...
    $database->commitTransaction();
} catch(\Exception $e) {
    $database->rollbackTransaction();
    throw $e;
}
```

PHPixie also supports transaction savepoints which can be used to for some more adavcenced behavior:

```
$name = $database->savepointTransaction();
$database->rollbackTransactionTo($name);
```

MongoDB
-------

[](#mongodb)

Querying MongoDB is very similar to querying SQL databases. Of course you can not use relational methods like `JOIN` and `HAVING` statements, transactions, etc. But instead you get additional features in addition:

```
$posts = $query
    ->collection('posts')
    // subdocument conditions
    ->where('author.name', 'Dracony')
    ->limit(1)
    ->offset(1)
    ->execute();

$connection->updateQuery()
    ->collection('posts')
    ->set('done', true)
    ->unset(array('started', 'inProgress'))
    ->execute();

$connection->insertQuery()
    ->collection('posts')
    ->batchData(array(
        array(
            'name' => 'Trixie'
        ),
        array(
            'name' => 'Stella'
        )
    ))
    ->execute();
```

An easier way of querying subdocuments can be achieved using subdocument groups:

```
//setting conditions for subdocuments
$query
    ->startOrNotSubdocumentGroup('author')
        ->where('name', 'Dracony')
    ->endGroup();

//setting conditions for subarray items
$query
    ->startOrNotSubarrayItemGroup('authors')
        ->where('name', 'Dracony')
    ->endGroup();
```

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity33

Limited adoption so far

Community24

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 91.8% 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 ~84 days

Recently: every ~269 days

Total

20

Last Release

2275d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2fd2ee997c779cf774247d3d4cde7d90491484f817032aab6dbc314857973b36?d=identicon)[dracony](/maintainers/dracony)

---

Top Contributors

[![dracony](https://avatars.githubusercontent.com/u/3127080?v=4)](https://github.com/dracony "dracony (212 commits)")[![dorantor](https://avatars.githubusercontent.com/u/391611?v=4)](https://github.com/dorantor "dorantor (9 commits)")[![rez1dent3](https://avatars.githubusercontent.com/u/5111255?v=4)](https://github.com/rez1dent3 "rez1dent3 (4 commits)")[![Parishop](https://avatars.githubusercontent.com/u/22610359?v=4)](https://github.com/Parishop "Parishop (3 commits)")[![einfallstoll](https://avatars.githubusercontent.com/u/619048?v=4)](https://github.com/einfallstoll "einfallstoll (1 commits)")[![corpsee](https://avatars.githubusercontent.com/u/1416706?v=4)](https://github.com/corpsee "corpsee (1 commits)")[![Nayfania](https://avatars.githubusercontent.com/u/4580316?v=4)](https://github.com/Nayfania "Nayfania (1 commits)")

---

Tags

databasemysqlsqlitepostgresql

### Embed Badge

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

```
[![Health](https://phpackages.com/badges/phpixie-database/health.svg)](https://phpackages.com/packages/phpixie-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)[ark/database

Light weight database abstraction

117.8k](/packages/ark-database)

PHPackages © 2026

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