PHPackages                             voku/simple-active-record - 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. voku/simple-active-record

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

voku/simple-active-record
=========================

Simple Active Record

1.8.0(6y ago)55611[1 issues](https://github.com/voku/simple-active-record/issues)[5 PRs](https://github.com/voku/simple-active-record/pulls)MITPHPPHP &gt;=7.0

Since Dec 21Pushed 1w ago3 watchersCompare

[ Source](https://github.com/voku/simple-active-record)[ Packagist](https://packagist.org/packages/voku/simple-active-record)[ Docs](https://github.com/voku/simple-active-record)[ RSS](/packages/voku-simple-active-record/feed)WikiDiscussions master Synced 3d ago

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

[![Build Status](https://camo.githubusercontent.com/4e814da4b4f0a5fe45f775ec26f19f01d3d9fe4c3e10983c133db2c8ef2d32e3/68747470733a2f2f7472617669732d63692e636f6d2f766f6b752f73696d706c652d6163746976652d7265636f72642e7376673f6272616e63683d6d6173746572)](https://travis-ci.com/voku/simple-active-record)[![Coverage Status](https://camo.githubusercontent.com/7ab2e228ef0864f3b4c6047a6a86fb7189cf59e8a5d3cd184f812784c260fcc6/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f766f6b752f73696d706c652d6163746976652d7265636f72642f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/voku/simple-active-record?branch=master)[![Codacy Badge](https://camo.githubusercontent.com/5a585ff51a1465fba48c3e3790ae3dd5a0ffe33411a08ccd284b64948196cba1/68747470733a2f2f6170692e636f646163792e636f6d2f70726f6a6563742f62616467652f47726164652f6462306236383166643462663433346561636561613532313336393865613365)](https://www.codacy.com/app/voku/simple-active-record)[![Latest Stable Version](https://camo.githubusercontent.com/6987f2b40439bd3935d99de2a64db187e6d573ed6ad1f72d4453a119292a9228/68747470733a2f2f706f7365722e707567782e6f72672f766f6b752f73696d706c652d6163746976652d7265636f72642f762f737461626c65)](https://packagist.org/packages/voku/simple-active-record)[![Total Downloads](https://camo.githubusercontent.com/5188c2b924cd6c16431d207db83ba02a34373553c086f1fb5d2011dd719331bf/68747470733a2f2f706f7365722e707567782e6f72672f766f6b752f73696d706c652d6163746976652d7265636f72642f646f776e6c6f616473)](https://packagist.org/packages/voku/simple-active-record)[![License](https://camo.githubusercontent.com/cae2cdb135e6d9e7b0e5d7792626f6458cf03cc33dab2ee44219b11bae980431/68747470733a2f2f706f7365722e707567782e6f72672f766f6b752f73696d706c652d6163746976652d7265636f72642f6c6963656e7365)](https://packagist.org/packages/voku/simple-active-record)[![Donate to this project using Paypal](https://camo.githubusercontent.com/0d6e4d8b50b5983a58205941b1a581b1305903393b7a39da574e3f60af3c7f5b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f70617970616c2d646f6e6174652d79656c6c6f772e737667)](https://www.paypal.me/moelleken)[![Donate to this project using Patreon](https://camo.githubusercontent.com/f9e075baad95563481d35174d43ef50757281abb6bc795d0f473fad452afa030/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f70617472656f6e2d646f6e6174652d79656c6c6f772e737667)](https://www.patreon.com/voku)

💍 Simple Active Record
======================

[](#ring-simple-active-record)

This is a simple Active Record Pattern compatible with PHP 7+ that provides a simple and *secure* interaction with your database using 💎 ["Simple MySQLi"](https://github.com/voku/simple-mysqli/) at its core. This is perfect for small scale applications such as cron jobs, facebook canvas campaigns or micro frameworks or sites.

### Get "Simple Active Record"

[](#get-simple-active-record)

You can download it from here, or require it using [composer](https://packagist.org/packages/voku/simple-mysqli).

```
  {
      "require": {
        "voku/simple-active-record": "1.*"
      }
  }
```

### Install via "composer require"

[](#install-via-composer-require)

```
  composer require voku/simple-active-record
```

- [Starting the driver](#starting-the-driver)
- [Multiton &amp;&amp; Singleton](#multiton--singleton)
- [Doctrine/DBAL as parent driver](#doctrinedbal-as-parent-driver)
- [Using the "ActiveRecord"-Class (OOP database-access)](#using-the-activerecord-class-oop-database-access)
    - [setDb(DB $db)](#setdbdb-db)
    - [insert() : bool|int](#insert--boolint)
    - [fetch(integer $id = null) : bool|\\ActiveRecord](#fetchinteger--id--null--boolactiverecord)
    - [fetchAll() : $this\[\]](#fetchall--this)
    - [update() : bool|int](#update--boolint)
    - [delete() : bool](#update--boolint)
    - [Active Record | SQL part functions](#active-record--sql-part-functions)
        - [select()](#select)
        - [from()](#from)
        - [join()](#join)
        - [where()](#where)
        - [group()](#group)
        - [order()](#order)
        - [limit()](#limit)
    - [Active Record | WHERE conditions](#active-record--where-conditions)
        - [equal()/eq()](#equaleq)
        - [notEqual()/ne()](#notequalne)
        - [greaterThan()/gt()](#greaterthangt)
        - [lessThan()/lt()](#lessthanlt)
        - [greaterThanOrEqual()/ge()/gte()](#greaterthanorequalgegte)
        - [lessThanOrEqual()/le()/lte()](#lessthanorequallelte)
        - [like()](#like)
        - [in()](#in)
        - [notIn()](#notin)
        - [isNull()](#isnull)
        - [isNotNull()/notNull()](#isnotnullnotnull)
    - [Active Record | Demo](#active-record---demo)
- [Logging and Errors](#logging-and-errors)
- [Changelog](#changelog)

### Starting the driver

[](#starting-the-driver)

```
  use voku\db\DB;

  require_once 'composer/autoload.php';

  $db = DB::getInstance('yourDbHost', 'yourDbUser', 'yourDbPassword', 'yourDbName');

  // example
  // $db = DB::getInstance('localhost', 'root', '', 'test');
```

### Multiton &amp;&amp; Singleton

[](#multiton--singleton)

You can use `DB::getInstance()` without any parameters and you will get your (as "singleton") first initialized connection. Or you can change the parameter and you will create an new "multiton"-instance which works like an singleton, but you need to use the same parameters again, otherwise (without the same parameter) you will get an new instance.

### Doctrine/DBAL as parent driver

[](#doctrinedbal-as-parent-driver)

```
  use voku\db\DB;

  require_once 'composer/autoload.php';

  $connectionParams = [
      'dbname'   => 'yourDbName',
      'user'     => 'yourDbUser',
      'password' => 'yourDbPassword',
      'host'     => 'yourDbHost',
      'driver'   => 'mysqli', // 'pdo_mysql' || 'mysqli'
      'charset'  => 'utf8mb4',
  ];
  $config = new \Doctrine\DBAL\Configuration();
  $doctrineConnection = \Doctrine\DBAL\DriverManager::getConnection(
      $connectionParams,
      $config
  );
  $doctrineConnection->connect();

  $db = DB::getInstanceDoctrineHelper($doctrineConnection);
```

### Using the "ActiveRecord"-Class (OOP database-access)

[](#using-the-activerecord-class-oop-database-access)

A simple implement of active record pattern via Arrayy.

#### setDb(DB $db)

[](#setdbdb-db)

set the DB connection.

```
  $db = DB::getInstance('YOUR_MYSQL_SERVER', 'YOUR_MYSQL_USER', 'YOUR_MYSQL_PW', 'YOUR_DATABASE');
  ActiveRecord::setDb($db);
```

#### insert() : bool|int

[](#insert--boolint)

This function can build insert SQL queries and can insert the current record into database. If insert was successful, it will return the new id, otherwise it will return false or true (if there are no dirty data).

```
  $user = new User();
  $user->name = 'demo';
  $user->password = password_hash('demo', PASSWORD_BCRYPT, ["cost" => 15]);
  $user_id = $user->insert();

  var_dump($user_id); // the new id
  var_dump($user->id); // also the new id
  var_dump($user->getPrimaryKey()); // also the new id
```

#### fetch(integer $id = null) : bool|\\ActiveRecord

[](#fetchinteger--id--null--boolactiverecord)

This function can fetch one record and assign in to current object. If you call this function with the $id parameter, it will fetch records by using the current primary-key-name.

```
  $user = new User();

  $user->notnull('id')->orderBy('id desc')->fetch();

  // OR //

  $user->fetch(1);

  // OR //

  $user->fetchById(1); // thows "FetchingException" if the ID did not exists

  // OR //

  $user->fetchByIdIfExists(1); // return NULL if the ID did not exists

  // OR //

  $user->fetchByHashId('fsfsdwldasdar'); // thows "FetchingException" if the ID did not exists

  // OR //

  $user->fetchByHashIdIfExists('fsfsdwldasdar'); // return NULL if the ID did not exists

  var_dump($user->id); // (int) 1
  var_dump($user->getPrimaryKey()); // (int) 1
```

#### fetchAll() : $this\[\]

[](#fetchall--this)

This function can fetch all records in the database and will return an array of ActiveRecord objects.

```
  $user = new User();

  $users = $user->fetchAll();

  // OR //

  $users = $user->fetchByIds([1]);

  // OR //

  $users = $user->fetchByIdsPrimaryKeyAsArrayIndex([1]);

  var_dump($users[0]->id) // (int) 1
  var_dump($users[0]->getPrimaryKey()); // (int) 1
```

#### update() : bool|int

[](#update--boolint)

This function can build update SQL queries and can update the current record in database, just write the dirty data into database. If update was successful, it will return the affected rows as int, otherwise it will return false or true (if there are no dirty data).

```
  $user = new User();
  $user->notnull('id')->orderBy('id desc')->fetch();
  $user->email = 'test@example.com';
  $user->update();
```

#### delete() : bool

[](#delete--bool)

This function can delete the current record in the database.

### Active Record | SQL part functions

[](#active-record--sql-part-functions)

#### select()

[](#select)

This function can set the select columns.

```
  $user = new User();
  $user->select('id', 'name')->fetch();
```

#### from()

[](#from)

This function can set the table to fetch record from.

```
  $user = new User();
  $user->select('id', 'name')->from('user')->fetch();
```

#### join()

[](#join)

This function can set the table to fetch record from.

```
  $user = new User();
  $user->join('contact', 'contact.user_id = user.id')->fetch();
```

#### where()

[](#where)

This function can set where conditions.

```
  $user = new User();
  $user->where('id=1 AND name="demo"')->fetch();
```

#### groupBy()

[](#groupby)

This function can set the "group by" conditions.

```
  $user = new User();
  $user->select('count(1) as count')->groupBy('name')->fetchAll();
```

#### orderBy()

[](#orderby)

This function can set the "order by" conditions.

```
  $user = new User();
  $user->orderBy('name DESC')->fetch();
```

#### limit()

[](#limit)

This function can set the "limit" conditions.

```
  $user = new User();
  $user->orderBy('name DESC')->limit(0, 1)->fetch();
```

### Active Record | WHERE conditions

[](#active-record--where-conditions)

#### equal()/eq()

[](#equaleq)

```
  $user = new User();
  $user->eq('id', 1)->fetch();
```

#### notEqual()/ne()

[](#notequalne)

```
  $user = new User();
  $user->ne('id', 1)->fetch();
```

#### greaterThan()/gt()

[](#greaterthangt)

```
  $user = new User();
  $user->gt('id', 1)->fetch();
```

#### lessThan()/lt()

[](#lessthanlt)

```
  $user = new User();
  $user->lt('id', 1)->fetch();
```

#### greaterThanOrEqual()/ge()/gte()

[](#greaterthanorequalgegte)

```
  $user = new User();
  $user->ge('id', 1)->fetch();
```

#### lessThanOrEqual()/le()/lte()

[](#lessthanorequallelte)

```
  $user = new User();
  $user->le('id', 1)->fetch();
```

#### like()

[](#like)

```
  $user = new User();
  $user->like('name', 'de')->fetch();
```

#### in()

[](#in)

```
  $user = new User();
  $user->in('id', [1, 2])->fetch();
```

#### notIn()

[](#notin)

```
  $user = new User();
  $user->notin('id', [1, 3])->fetch();
```

#### isNull()

[](#isnull)

```
  $user = new User();
  $user->isnull('id')->fetch();
```

#### isNotNull()/notNull()

[](#isnotnullnotnull)

```
  $user = new User();
  $user->isNotNull('id')->fetch();
```

### Active Record | Demo

[](#active-record--demo)

#### Include &amp;&amp; Init

[](#include--init)

```
use voku\db\DB;
use voku\db\ActiveRecord;

require_once 'composer/autoload.php';

$db = DB::getInstance('YOUR_MYSQL_SERVER', 'YOUR_MYSQL_USER', 'YOUR_MYSQL_PW', 'YOUR_DATABASE');
ActiveRecord::setDb($db);
```

#### Define Class

[](#define-class)

```
namespace demo;

use voku\db\ActiveRecord;

/**
 * @property int       $id
 * @property string    $name
 * @property string    $password
 * @property Contact[] $contacts
 * @property Contact   $contacts_with_backref
 * @property Contact   $contact
 */
class User extends ActiveRecord {
  public $table = 'user';

  public $primaryKey = 'id';

  protected function init()
  {
      $this->addRelation(
          'contacts',
          self::HAS_MANY,
          FoobarContact::class,
          'user_id'
      );

      $this->addRelation(
          'contacts_with_backref',
          self::HAS_MANY,
          FoobarContact::class,
          'user_id',
          null,
          'user'
      );

      $this->addRelation(
        'contact',
          self::HAS_ONE,
          FoobarContact::class,
          'user_id',
          [
              self::SQL_WHERE => '1 = 1',
              self::SQL_ORDER => 'id desc',
          ]
      );
  }
}

/**
 * @property int    $id
 * @property int    $user_id
 * @property string $email
 * @property string $address
 * @property User   $user_with_backref
 * @property User   $user
 */
class Contact extends ActiveRecord {
  public $table = 'contact';

  public $primaryKey = 'id';

  protected function init()
  {
      $this->addRelation(
          'user_with_backref',
          self::BELONGS_TO,
          FoobarUser::class,
          'user_id',
          null,
          'contact'
      );

      $this->addRelation(
          'user',
          self::BELONGS_TO,
          FoobarUser::class,
          'user_id'
      );
  }
}
```

#### Init data (for testing - use migrations for this step, please)

[](#init-data-for-testing---use-migrations-for-this-step-please)

```
CREATE TABLE IF NOT EXISTS user (
  id INTEGER PRIMARY KEY,
  name TEXT,
  password TEXT
);

CREATE TABLE IF NOT EXISTS contact (
  id INTEGER PRIMARY KEY,
  user_id INTEGER,
  email TEXT,
  address TEXT
);
```

#### Insert one User into database.

[](#insert-one-user-into-database)

```
use demo\User;

$user = new User();
$user->name = 'demo';
$user->password = password_hash('demo', PASSWORD_BCRYPT, ["cost" => 15]);
$user_id = $user->insert();

var_dump($user_id); // the new id
var_dump($user->id); // also the new id
var_dump($user->getPrimaryKey()); // also the new id
```

#### Insert one Contact belongs the current user.

[](#insert-one-contact-belongs-the-current-user)

```
use demo\Contact;

$contact = new Contact();
$contact->address = 'test';
$contact->email = 'test1234456@domain.com';
$contact->user_id = $user->id;

var_dump($contact->insert()); // the new id
var_dump($contact->id); // also the new id
var_dump($contact->getPrimaryKey()); // also the new id
```

#### Example to using relations

[](#example-to-using-relations)

```
use demo\User;
use demo\Contact;

$user = new User();

// fetch one user
var_dump($user->notnull('id')->orderBy('id desc')->fetch());

echo "\nContact of User # {$user->id}\n";
// get contacts by using relation:
//   'contacts' => [self::HAS_MANY, 'demo\Contact', 'user_id'],
var_dump($user->contacts);

$contact = new Contact();

// fetch one contact
var_dump($contact->fetch());

// get user by using relation:
//    'user' => [self::BELONGS_TO, 'demo\User', 'user_id'],
var_dump($contact->user);
```

### Changelog

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md).

### Support

[](#support)

For support and donations please visit [Github](https://github.com/voku/simple-active-record/) | [Issues](https://github.com/voku/simple-active-record/issues) | [PayPal](https://paypal.me/moelleken) | [Patreon](https://www.patreon.com/voku).

For status updates and release announcements please visit [Releases](https://github.com/voku/simple-active-record/releases) | [Twitter](https://twitter.com/suckup_de) | [Patreon](https://www.patreon.com/voku/posts).

For professional support please contact [me](https://about.me/voku).

### Thanks

[](#thanks)

- Thanks to [GitHub](https://github.com) (Microsoft) for hosting the code and a good infrastructure including Issues-Managment, etc.
- Thanks to [IntelliJ](https://www.jetbrains.com) as they make the best IDEs for PHP and they gave me an open source license for PhpStorm!
- Thanks to [Travis CI](https://travis-ci.com/) for being the most awesome, easiest continous integration tool out there!
- Thanks to [StyleCI](https://styleci.io/) for the simple but powerfull code style check.
- Thanks to [PHPStan](https://github.com/phpstan/phpstan) &amp;&amp; [Psalm](https://github.com/vimeo/psalm) for relly great Static analysis tools and for discover bugs in the code!

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance60

Regular maintenance activity

Popularity19

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 93.9% 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 ~47 days

Recently: every ~35 days

Total

11

Last Release

2225d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6456fe693db197c458272cb758bf78958bc7d3e787ccd59db4bf3cf41654316a?d=identicon)[voku](/maintainers/voku)

---

Top Contributors

[![voku](https://avatars.githubusercontent.com/u/264695?v=4)](https://github.com/voku "voku (31 commits)")[![dependabot-support](https://avatars.githubusercontent.com/u/112581971?v=4)](https://github.com/dependabot-support "dependabot-support (1 commits)")[![renovate[bot]](https://avatars.githubusercontent.com/in/2740?v=4)](https://github.com/renovate[bot] "renovate[bot] (1 commits)")

---

Tags

active-recordactiverecorddatabasehacktoberfestmysqlphpphp7sqlphpdbactive-recordsimple db

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/voku-simple-active-record/health.svg)

```
[![Health](https://phpackages.com/badges/voku-simple-active-record/health.svg)](https://phpackages.com/packages/voku-simple-active-record)
```

###  Alternatives

[voku/simple-mysqli

Simple MySQLi library

4547.9k4](/packages/voku-simple-mysqli)[swoft/db

swoft database component

24167.4k11](/packages/swoft-db)[stefangabos/zebra_database

An advanced, compact and lightweight MySQL database wrapper library, built around PHP's MySQLi extension.

11812.0k](/packages/stefangabos-zebra-database)[simple-swoole/db

A db component for Simps.

216.3k3](/packages/simple-swoole-db)

PHPackages © 2026

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