PHPackages                             piko/db-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. piko/db-record

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

piko/db-record
==============

A lightweight Active Record helper built on top of PDO.

v3.1(1mo ago)01172LGPL-3.0-or-laterPHPPHP &gt;=8.1.0CI passing

Since Oct 10Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/piko-framework/db-record)[ Packagist](https://packagist.org/packages/piko/db-record)[ Docs](https://github.com/piko-framework/db-record)[ RSS](/packages/piko-db-record/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (13)Versions (13)Used By (2)

Piko Db Record
==============

[](#piko-db-record)

[![build](https://github.com/piko-framework/db-record/actions/workflows/php.yml/badge.svg)](https://github.com/piko-framework/db-record/actions/workflows/php.yml)[![Coverage Status](https://camo.githubusercontent.com/009bd58207d4e8e204a9c764ee3419c267af78c3a63efb7b0f173ac349fc0ac7/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f70696b6f2d6672616d65776f726b2f64622d7265636f72642f62616467652e7376673f6272616e63683d6d61696e)](https://coveralls.io/github/piko-framework/db-record?branch=main)

Piko Db Record is a lightweight Active Record implementation built on top of PDO.

It has been tested with:

- SQLite
- MySQL
- PostgreSQL
- MSSQL

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

[](#installation)

It is recommended to install Piko Db Record with Composer:

```
composer require piko/db-record
```

Documentation
-------------

[](#documentation)

Usage
-----

[](#usage)

First, ensure autoloading is available:

```
require 'vendor/autoload.php';
```

### Define your model (attributes)

[](#define-your-model-attributes)

```
use Piko\DbRecord;
use Piko\DbRecord\Attribute\Table;
use Piko\DbRecord\Attribute\Column;

#[Table(name: 'contact')]
class Contact extends DbRecord
{
    #[Column(primaryKey: true)]
    public ?int $id = null;

    #[Column]
    public ?string $firstname = null;

    #[Column]
    public ?string $lastname = null;

    #[Column]
    public ?bool $active = false;
}
```

### Optional: map DB columns to different PHP property names

[](#optional-map-db-columns-to-different-php-property-names)

```
use Piko\DbRecord;
use Piko\DbRecord\Attribute\Table;
use Piko\DbRecord\Attribute\Column;

#[Table(name: 'contact')]
class ContactMapped extends DbRecord
{
    #[Column(name: 'id', primaryKey: true)]
    public ?int $contactId = null;

    #[Column(name: 'firstname')]
    public ?string $firstName = null;

    #[Column(name: 'lastname')]
    public ?string $lastName = null;

    #[Column(name: 'active')]
    public ?bool $isActive = false;
}
```

You can then use either mapped property names (`$contact->firstName`) or underlying column names (`$contact->firstname`).

### Optional: custom cast types (`float`, `decimal`, `datetime_immutable`, `datetime_mutable`, `json`)

[](#optional-custom-cast-types-float-decimal-datetime_immutable-datetime_mutable-json)

```
use DateTimeImmutable;
use Piko\DbRecord;
use Piko\DbRecord\Attribute\Table;
use Piko\DbRecord\Attribute\Column;

#[Table(name: 'contact')]
class ContactAdvancedTypes extends DbRecord
{
    #[Column(primaryKey: true)]
    public ?int $id = null;

    #[Column(type: 'float')]
    public ?float $income = null;

    #[Column(name: 'name', type: 'json')]
    public ?array $nameData = null;

    #[Column(name: 'lastname', type: 'datetime_immutable')]
    public ?DateTimeImmutable $lastSeenAt = null;

    #[Column(name: 'firstname', type: 'decimal', scale: 4)]
    public ?string $balance = null;
}
```

- `float` values are cast to PHP `float`.
- `decimal` values are normalized as strings. With `scale`, values are rounded/formatted to that precision.
- `datetime_immutable` values are cast to `DateTimeImmutable`.
- `datetime_mutable` values are cast to `DateTime`.
- `json` values are stored as JSON strings and exposed as PHP arrays.

`datetime` remains supported as an alias of `datetime_immutable` for backward compatibility.

### Optional: legacy/manual schema (including string primary keys)

[](#optional-legacymanual-schema-including-string-primary-keys)

```
use Piko\DbRecord;

class ContactStringPk extends DbRecord
{
    protected string $tableName = 'contact';
    protected string $primaryKey = 'firstname';

    protected array $schema = [
        'firstname' => self::TYPE_STRING,
        'lastname'  => self::TYPE_STRING,
    ];
}
```

With non-integer primary keys, set the key before `save()` when creating a new row:

```
$contact = new ContactStringPk($db);
$contact->firstname = 'pk_insert';
$contact->lastname = 'Doe';
$contact->save(); // INSERT with provided primary key
```

### Setup database connection

[](#setup-database-connection)

Create a PDO instance and initialize schema:

```
$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = firstname = 'John';
$contact->lastname = 'Doe';
$contact->active = true;
$contact->save();

echo "Contact id: {$contact->id}"; // Contact id : 1
```

#### Read

[](#read)

```
$contact = (new Contact($db))->load(1);

var_dump($contact->firstname); // John

$exists = (new Contact($db))->exists(1); // true
```

#### Update

[](#update)

```
$contact->lastname = 'Doe Jr.';
$contact->save();
```

#### Delete

[](#delete)

```
$contact->delete();
```

Known limitations
-----------------

[](#known-limitations)

- Composite primary keys are not supported.
- `save()` updates all mapped columns (no dirty-field tracking yet).
- For auto-increment integer primary keys, inserted IDs are filled from `PDO::lastInsertId()` when available.
- For non-integer (e.g. string) primary keys, your application typically provides the key value.
- `save()` performs an INSERT when the primary key is `null` or does not exist in database yet; otherwise it performs an UPDATE.

Running tests
-------------

[](#running-tests)

Run full checks (all database targets + coding standards + static analysis):

```
composer tests
```

Run tests for one database only:

```
composer phpunit:sqlite
composer phpunit:mysql
composer phpunit:pgsql
composer phpunit:mssql
```

Support
-------

[](#support)

If you encounter issues or have questions, feel free to open an issue on GitHub.

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance83

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity63

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

Recently: every ~162 days

Total

12

Last Release

35d ago

Major Versions

v1.1 → v2.02022-11-04

v2.2.3 → v3.02026-07-13

PHP version history (2 changes)v1.0PHP &gt;=7.1.0

v2.1PHP &gt;=8.1.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/001b70c85d853a2aae5f1bf74a1ff7ad77ffcec2d423090d67293bde99158350?d=identicon)[ilhooq](/maintainers/ilhooq)

---

Top Contributors

[![ilhooq](https://avatars.githubusercontent.com/u/1500886?v=4)](https://github.com/ilhooq "ilhooq (42 commits)")

---

Tags

databasesqlrecordactive-record

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/piko-db-record/health.svg)

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

###  Alternatives

[doctrine/dbal

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

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

The Illuminate Database package.

2.8k55.8M13.1k](/packages/illuminate-database)[catfan/medoo

The lightweight PHP database framework to accelerate development

5.0k1.6M214](/packages/catfan-medoo)[ifsnop/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

1.3k6.2M84](/packages/ifsnop-mysqldump-php)[propel/propel1

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

8351.6M88](/packages/propel-propel1)[usmanhalalit/pixie

A lightweight, expressive, framework agnostic query builder for PHP.

6762.3M16](/packages/usmanhalalit-pixie)

PHPackages © 2026

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