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

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

liftkit/database
================

Database library for LiftKit

v2.25.1(4d ago)12.3k1LGPL-2.1-onlyPHPCI failing

Since Feb 26Pushed 2y ago1 watchersCompare

[ Source](https://github.com/liftkit/database)[ Packagist](https://packagist.org/packages/liftkit/database)[ RSS](/packages/liftkit-database/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (8)Versions (74)Used By (1)Security (1)

LiftKit database library
========================

[](#liftkit-database-library)

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

[](#installation)

```
composer require liftkit/database

```

Let's jump right in to some examples.

Connection
----------

[](#connection)

### Establish a connection

[](#establish-a-connection)

```
use LiftKit\Database\Connection\MySql;
use LiftKit\DependencyInjection\Container\Container;
use LiftKit\Database\Cache\Cache;
use PDO;

$connection = new MySql(
  new Container,
	new Cache,
	new PDO('connectionString', 'username', 'password')
);
```

### Run a raw SQL query

[](#run-a-raw-sql-query)

```
$results = $connection->query(
  "
    SELECT *
    FROM tbl
  "
);
```

### Using placeholders

[](#using-placeholders)

```
$connection->query(
  "
    SELECT *
    FROM tbl
    WHERE col1 = ?
      AND col2 = ?
  ",
  [
    'val1',
    'val2',
  ]
);
```

Result objects
==============

[](#result-objects)

### Loop through results

[](#loop-through-results)

```
// NOTE:
// Results are not loaded into memory. Instead they are
// wrapped by an object of the class
// \LiftKit\Database\Result\Result

$results = $connection->query(
	"
		SELECT *
		FROM tbl
	"
);

foreach ($results as $row) {
  echo 'column "name" = ' . $row['name'] . PHP_EOL;
  echo 'column "id" = ' . $row['id'] . PHP_EOL;
}
```

### Fetch a single column as an array

[](#fetch-a-single-column-as-an-array)

```
foreach ($results->fetchColumn('id') as $id) {
	echo $id . PHP_EOL;
}
// '1'
// '2'
// ...
```

### Fetch all rows as an array of entities

[](#fetch-all-rows-as-an-array-of-entities)

```
foreach ($results->fetchAll() as $row) {
	// Do something with $row['column']
}
```

### Fetch all rows as an array of associative arrays

[](#fetch-all-rows-as-an-array-of-associative-arrays)

```
foreach ($results->flatten() as $row) {
	// Do something with $row['column']
}
```

Query builder
-------------

[](#query-builder)

### New query

[](#new-query)

```
use LiftKit\Database\Query\Query;

/**
 * @var Query $query
 */
$query = $connection->createQuery();
```

### Simple select query

[](#simple-select-query)

```
// SELECT field1, field2
// FROM tbl
// WHERE field1 = 'val1'

$results = $query->select('field1', 'field2')
  ->from('tbl')
  ->whereEqual('field1', 'val1')
  ->execute();
```

### More complicated select query

[](#more-complicated-select-query)

Note that the method `$connection->quoteIdentifier()` is called on the right parameters. That's because the right parameter is expected to be a value. If it is instead a SQL identifier, it must be quoted.

This example shows the query with MySQL style identifier quotes to illustrate the point. Note the difference between the `JOIN` conditions and the `WHERE` conditions.

```
use LiftKit\Database\Query\Condition\Condition;

// SELECT `field1`, `field2`
// FROM `tbl`
// LEFT JOIN `other_tbl` ON (
//  `tbl`.`field1` = `other_tbl`.`field1`
//  OR `tbl`.`field2` > `other_tbl`.field2`
// )
// WHERE `tbl`.`field1` = 'val1'
//    OR `other_tbl`.`field2` = 'val2'
// GROUP BY `tbl`.`field3`, `tbl`.`field4`
// HAVING `tbl`.`field1` < 1
// ORDER BY `tbl`.`field5` ASC, `tbl`.`field6` DESC

$results = $query->select('field1', 'field2')
  ->from('tbl')
  ->leftJoin(
    'other_tbl',
    $connection->createCondition()
    	->equal(
     		'tbl.field1',
     		$connection->quoteIdentifier('other_tbl.field1')
    	)
    	->orGreaterThan(
     		'tbl.field2',
     		$connection->quoteIdentifier('other_tbl.field2')
    	)
  )
  ->whereEqual('tbl1.field1', 'val1')
  ->orWhereEqual('other_tbl.field2', 'val2')
  ->groupBy('tbl.field3')
  ->groupBy('tbl.field4')
  ->havingLessThan('tbl.field1', 1)
  ->orderBy('tbl.field5', Query::ORDER_ASC)
  ->orderBy('tbl.field6', Query::ORDER_DESC)
  ->execute();
```

### Update query

[](#update-query)

Note that update queries can utilize conditions the same as select statements.

```
// UPDATE tbl
// SET field2 = 'val2', field3 = 'val3'
// WHERE tbl.id = 2

$query->update()
  ->table('tbl')
  ->set(
    [
      'field2' => 'val2',
      'field3' => 'val3',
    ]
  )
  ->whereEqual('tbl.id', 2)
  ->execute();
```

### Insert query

[](#insert-query)

Insert queries return their insert ID.

```
// INSERT INTO tbl
// SET field2 = 'val2', field3 = 'val3'

$id = $query->insert()
  ->into('tbl')
  ->set(
    [
      'field2' => 'val2',
      'field3' => 'val3',
    ]
  )
  ->execute();
```

### Delete query

[](#delete-query)

Note that delete queries can use conditions the same as select queries.

```
// DELETE tbl.*
// FROM tbl
// WHERE id = 1

$query->delete()
  ->from('tbl')
  ->whereEqual('id', 1)
  ->execute();
```

Subqueries
----------

[](#subqueries)

Subqueries can be substituted pretty much anywhere a value or identifier can be.

Note: This is also an example of how to use raw SQL instead of escaped values in your queries using the method `$connection->createRaw()`. Select arguments, like the left had side of conditions, will be quoted as an identifier unless otherwise specified.

```
// SELECT *
// FROM tbl1
// WHERE
// ( SELECT COUNT(*)
//   FROM tbl2
//   WHERE tbl1.id = tbl2.tbl1_id
// ) = 1

$results = $query->select('*')
  ->from('tbl1')
  ->whereEqual(
    $connection->createQuery()
      ->select($connection->createRaw('COUNT(*)'))
      ->from('tbl2')
      ->whereEqual(
      	'tbl1.id',
      	$connection->quoteIdentifier('tb2.tbl1_id')
      ),
    1
  )
  ->execute();
```

### Composing parts of queries

[](#composing-parts-of-queries)

This comes in hand for extracting away parts of queries you use often, while retaining the ability to combine them with other queries.

Let's say you have a function that returns all of the rows from `tbl`.

```
function getAllTblRows ()
{
  return $connection->createQuery()
  	->select('*')
    ->from('tbl')
    ->execute();
}

// SELECT *
// FROM tbl

$results = getActiveTblRows();
```

Now you need another query which select only records which are active from `tbl`. Notice the additions to `getAllTblRows`.

```
function getAllTblRows (Query $inputQuery = null)
{
  return $connection->createQuery()
  	->select('*')
    ->from('tbl')
    ->composeWith($inputQuery)
    ->execute();
}

function getActiveTblRows ()
{
  $query = $connection->createQuery()
  	->whereEqual('active', 1);

  return getAllTblRows($query);
}

// SELECT *
// FROM tbl
// WHERE active = 1

$results = getActiveTblRows();
```

Table objects
-------------

[](#table-objects)

Table objects are meant to reduce the boilerplate you need to place in your query builder queries.

### Fetching multiple rows

[](#fetching-multiple-rows)

```
use LiftKit\Database\Schema\Schema;
use LiftKit\Database\Schema\Table\Table;

// We'll get back to schemas in a moment

$table = new Table(
	$connection,
	new Schema($connection),
	'tbl'
);

// SELECT *
// FROM tbl

$results = $tbl->getRows();
```

### Fetching multiple rows with composed query

[](#fetching-multiple-rows-with-composed-query)

```
// SELECT *
// FROM tbl
// WHERE active = 1

$results = $table->getRows(
	$connection->createQuery()
		->whereEqual('active', 1)
);
```

### Fetching a single row

[](#fetching-a-single-row)

```
// SELECT *
// FROM tbl
// WHERE id = 1
// LIMIT 1

$row = $table->getRow(1);

// 'val1'
echo $row['field1'];

// 'val2'
echo $row['field2'];
```

### Inserting a new row

[](#inserting-a-new-row)

```
// INSERT INTO tbl
// SET field1 = 'val1', field2 = 'val2'

$id = $table->insertRow(
	[
		'field1' => 'val1',
		'field2' => 'val2',
	]
);
```

### Updating a row

NOTE: The library will auto-detect the primary key column and create an equal condition on that column.

```php

// UPDATE tbl
// SET field1 = 'val1', field2 = 'val2'
// WHERE id = 1

$table->updateRow(
	[
		'id'     => 1,
		'field1' => 'val1',
		'field2' => 'val2',
	]
);
```

### Deleting a row

```php
// DELETE FROM tbl
// WHERE id = 1

$table->deleteRow(1);
```

More info on table objects, relations, and entities coming soon!
```

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance55

Moderate activity, may be stable

Popularity21

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity78

Established project with proven stability

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

Recently: every ~300 days

Total

73

Last Release

4d ago

Major Versions

v1.1.0-alpha → v2.0.02015-02-28

### Community

Maintainers

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

---

Top Contributors

[![rwstream9](https://avatars.githubusercontent.com/u/1824185?v=4)](https://github.com/rwstream9 "rwstream9 (141 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k117.2M118](/packages/jdorn-sql-formatter)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8351.6M87](/packages/propel-propel1)[pgvector/pgvector

pgvector support for PHP

198741.5k12](/packages/pgvector-pgvector)[jfelder/oracledb

Oracle DB driver for Laravel

11518.4k](/packages/jfelder-oracledb)

PHPackages © 2026

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