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

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

webfiori/database
=================

Database abstraction layer of WebFiori framework.

2.0.1(2mo ago)533.7k—0%[1 issues](https://github.com/WebFiori/database/issues)1MITPHPPHP &gt;=8.1CI passing

Since Oct 28Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/WebFiori/database)[ Packagist](https://packagist.org/packages/webfiori/database)[ RSS](/packages/webfiori-database/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (89)Used By (1)

Webfiori Database Abstraction Layer
===================================

[](#webfiori-database-abstraction-layer)

Database abstraction layer of WebFiori framework.

 [ ![PHP 8 Build Status](https://github.com/WebFiori/database/actions/workflows/php85.yaml/badge.svg?branch=main) ](https://github.com/WebFiori/database/actions) [ ![CodeCov](https://camo.githubusercontent.com/c68e7feb08abe3aeb32b404e668c5ab7610fc50ba05d3833a16a0277fbdf2b62/68747470733a2f2f636f6465636f762e696f2f67682f57656246696f72692f64617461626173652f6272616e63682f6d61696e2f67726170682f62616467652e7376673f746f6b656e3d63444636437847544669) ](https://codecov.io/gh/WebFiori/database) [ ![Quality Checks](https://camo.githubusercontent.com/c47d1ebd999a1e75705a1bb3aba3532582af99634dde7bcfd5d8894d28f7a4b8/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d57656246696f72695f6461746162617365266d65747269633d616c6572745f737461747573) ](https://sonarcloud.io/dashboard?id=WebFiori_database) [ ![Version](https://camo.githubusercontent.com/67d0010de8f261ec7d312087e1e04b5a42693ed03799fa202c057e46d6c0afd7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f57656246696f72692f64617461626173652e7376673f6c6162656c3d6c6174657374) ](https://github.com/WebFiori/database/releases) [ ![Downloads](https://camo.githubusercontent.com/4d7b6c617f46a8e19a5eb25c706e121e8bf3be77a798925fd6c9cfe8962ee2b7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f77656266696f72692f64617461626173653f636f6c6f723d6c696768742d677265656e) ](https://packagist.org/packages/webfiori/database)

Content
-------

[](#content)

- [Supported PHP Versions](#supported-php-versions)
- [Supported Databases](#supported-databases)
- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
    - [Connecting to Database](#connecting-to-database)
    - [Running Basic SQL Queries](#running-basic-sql-queries)
    - [Building Database Structure](#building-database-structure)
    - [Repository Pattern](#repository-pattern)
    - [Active Record Pattern](#active-record-pattern)
    - [Entity Generation](#entity-generation)
    - [Database Migrations](#database-migrations)
    - [Database Seeders](#database-seeders)
    - [Performance Monitoring](#performance-monitoring)
    - [Transactions](#transactions)

Supported PHP Versions
----------------------

[](#supported-php-versions)

Build Status[![](https://github.com/WebFiori/database/actions/workflows/php81.yaml/badge.svg?branch=main)](https://github.com/WebFiori/database/actions/workflows/php81.yaml)[![](https://github.com/WebFiori/database/actions/workflows/php82.yaml/badge.svg?branch=main)](https://github.com/WebFiori/database/actions/workflows/php82.yaml)[![](https://github.com/WebFiori/database/actions/workflows/php83.yaml/badge.svg?branch=main)](https://github.com/WebFiori/database/actions/workflows/php83.yaml)[![](https://github.com/WebFiori/database/actions/workflows/php84.yaml/badge.svg?branch=main)](https://github.com/WebFiori/database/actions/workflows/php84.yaml)[![](https://github.com/WebFiori/database/actions/workflows/php85.yaml/badge.svg?branch=main)](https://github.com/WebFiori/database/actions/workflows/php85.yaml)Supported Databases
-------------------

[](#supported-databases)

- MySQL
- MSSQL

Features
--------

[](#features)

- Building your database structure within PHP
- Fast and easy to use query builder
- Database abstraction which makes it easy to migrate your system to different DBMS
- Repository pattern with `AbstractRepository` for clean data access
- Active Record pattern support for rapid development
- PHP 8 attributes for table definitions
- Database migrations and seeders
- Performance monitoring and query analysis
- Entity generation for object-relational mapping
- Transaction support with automatic rollback

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

[](#installation)

To install the library using composer, add following dependency to `composer.json`: `"webfiori/database":"*"`

Usage
-----

[](#usage)

### Connecting to Database

[](#connecting-to-database)

Connecting to a database is simple. First step is to define database connection information using the class `ConnectionInfo`. Later, the instance can be used to establish a connection to the database using the class `Database`.

```
use WebFiori\Database\ConnectionInfo;
use WebFiori\Database\Database;

$connection = new ConnectionInfo('mysql', 'root', '123456', 'testing_db');
$database = new Database($connection);
```

### Running Basic SQL Queries

[](#running-basic-sql-queries)

For every query, the table must be specified using `Database::table(string $tblName)`. The method returns an `AbstractQuery` instance with methods for building queries:

- `insert(array $cols)`: Construct an insert query.
- `select(array $cols)`: Construct a select query.
- `update(array $cols)`: Construct an update query.
- `delete()`: Construct a delete query.
- `where($col, $val)`: Adds a condition to the query.

After building the query, call `execute()` to run it.

```
// Insert
$database->table('posts')->insert([
    'title' => 'Super New Post',
    'author' => 'Me'
])->execute();

// Select
$resultSet = $database->table('posts')
    ->select()
    ->where('author', 'Ibrahim')
    ->execute();

foreach ($resultSet as $record) {
    echo $record['title'];
}

// Update
$database->table('posts')->update([
    'title' => 'Updated Title',
])->where('id', 1)->execute();

// Delete
$database->table('posts')->delete()->where('id', 1)->execute();
```

### Building Database Structure

[](#building-database-structure)

Define database structure in PHP code using blueprints:

```
use WebFiori\Database\ColOption;
use WebFiori\Database\DataType;

$database->createBlueprint('users')->addColumns([
    'id' => [
        ColOption::TYPE => DataType::INT,
        ColOption::PRIMARY => true,
        ColOption::AUTO_INCREMENT => true
    ],
    'name' => [
        ColOption::TYPE => DataType::VARCHAR,
        ColOption::SIZE => 100
    ],
    'email' => [
        ColOption::TYPE => DataType::VARCHAR,
        ColOption::SIZE => 150
    ]
]);

// Create the table
$database->table('users')->createTable()->execute();
```

### Repository Pattern

[](#repository-pattern)

The `AbstractRepository` class provides a clean way to handle data access with separation between entities and database logic.

#### Creating an Entity

[](#creating-an-entity)

```
class Product {
    public ?int $id = null;
    public string $name;
    public float $price;
}
```

#### Creating a Repository

[](#creating-a-repository)

```
use WebFiori\Database\Repository\AbstractRepository;

class ProductRepository extends AbstractRepository {
    protected function getTableName(): string {
        return 'products';
    }

    protected function getIdField(): string {
        return 'id';
    }

    protected function toEntity(array $row): object {
        $product = new Product();
        $product->id = (int) $row['id'];
        $product->name = $row['name'];
        $product->price = (float) $row['price'];
        return $product;
    }

    protected function toArray(object $entity): array {
        return [
            'id' => $entity->id,
            'name' => $entity->name,
            'price' => $entity->price
        ];
    }
}
```

#### Using the Repository

[](#using-the-repository)

```
$repo = new ProductRepository($database);

// Create
$product = new Product();
$product->name = 'Widget';
$product->price = 29.99;
$repo->save($product);

// Read
$product = $repo->findById(1);
$allProducts = $repo->findAll();

// Update
$product->price = 24.99;
$repo->save($product);

// Delete
$repo->deleteById(1);

// Pagination
$page = $repo->paginate(page: 1, perPage: 20);
```

### Active Record Pattern

[](#active-record-pattern)

For rapid development, you can merge entity and repository into a single model class:

```
use WebFiori\Database\Attributes\Column;
use WebFiori\Database\Attributes\Table;
use WebFiori\Database\DataType;
use WebFiori\Database\Repository\AbstractRepository;

#[Table(name: 'articles')]
class Article extends AbstractRepository {
    #[Column(type: DataType::INT, primary: true, autoIncrement: true)]
    public ?int $id = null;

    #[Column(type: DataType::VARCHAR, size: 200)]
    public string $title = '';

    #[Column(type: DataType::TEXT)]
    public string $content = '';

    protected function getTableName(): string { return 'articles'; }
    protected function getIdField(): string { return 'id'; }

    protected function toEntity(array $row): object {
        $article = new self($this->db);
        $article->id = (int) $row['id'];
        $article->title = $row['title'];
        $article->content = $row['content'];
        return $article;
    }

    protected function toArray(object $entity): array {
        return [
            'id' => $entity->id,
            'title' => $entity->title,
            'content' => $entity->content
        ];
    }
}
```

Usage:

```
// Create and save
$article = new Article($database);
$article->title = 'Hello World';
$article->content = 'My first article';
$article->save();

// Query
$all = $article->findAll();
$one = $article->findById(1);

// Update
$article->title = 'Updated Title';
$article->save();

// Delete
$article->deleteById();

// Reload from database
$fresh = $article->reload();
```

### Entity Generation

[](#entity-generation)

Generate entity classes from table blueprints:

```
$blueprint = $database->getTable('users');

$generator = $blueprint->getEntityGenerator('User', __DIR__, 'App\\Entity');
$generator->generate();
```

### Database Migrations

[](#database-migrations)

Version control your database schema changes:

```
use WebFiori\Database\Schema\AbstractMigration;

class CreateUsersTable extends AbstractMigration {
    public function up(Database $db): void {
        $db->createBlueprint('users')->addColumns([
            'id' => [ColOption::TYPE => DataType::INT, ColOption::PRIMARY => true, ColOption::AUTO_INCREMENT => true],
            'name' => [ColOption::TYPE => DataType::VARCHAR, ColOption::SIZE => 100]
        ]);
        $db->table('users')->createTable()->execute();
    }

    public function down(Database $db): void {
        $db->raw("DROP TABLE users")->execute();
    }
}
```

Run migrations:

```
use WebFiori\Database\Schema\SchemaRunner;

$runner = new SchemaRunner($connectionInfo);
$runner->discoverFromPath(__DIR__ . '/migrations', 'App\\Migrations');
$runner->createSchemaTable();
$runner->apply();
```

### Database Seeders

[](#database-seeders)

Populate your database with sample data:

```
use WebFiori\Database\Schema\AbstractSeeder;

class UsersSeeder extends AbstractSeeder {
    public function run(Database $db): void {
        $db->table('users')->insert([
            'name' => 'Administrator',
            'email' => 'admin@example.com'
        ])->execute();
    }
}
```

### Performance Monitoring

[](#performance-monitoring)

Track and analyze query performance:

```
use WebFiori\Database\Performance\PerformanceOption;

$database->setPerformanceConfig([
    PerformanceOption::ENABLED => true,
    PerformanceOption::SLOW_QUERY_THRESHOLD => 50
]);

// Execute queries...

$analyzer = $database->getPerformanceMonitor()->getAnalyzer();
echo "Total queries: " . $analyzer->getQueryCount();
echo "Slow queries: " . $analyzer->getSlowQueryCount();
```

### Transactions

[](#transactions)

Execute multiple operations as a single unit:

```
$database->transaction(function (Database $db) {
    $db->table('users')->insert(['name' => 'John'])->execute();
    $db->table('profiles')->insert([
        'user_id' => $db->getLastInsertId(),
        'bio' => 'Developer'
    ])->execute();
});
```

Examples
--------

[](#examples)

See the [examples](examples/) directory for complete working examples:

- [01-basic-connection](examples/01-basic-connection/) - Database connections
- [02-basic-queries](examples/02-basic-queries/) - CRUD operations
- [03-table-blueprints](examples/03-table-blueprints/) - Table structures
- [04-entity-mapping](examples/04-entity-mapping/) - Entity generation
- [05-transactions](examples/05-transactions/) - Transaction handling
- [06-migrations](examples/06-migrations/) - Schema migrations
- [07-seeders](examples/07-seeders/) - Data seeding
- [08-performance-monitoring](examples/08-performance-monitoring/) - Query analysis
- [09-multi-result-queries](examples/09-multi-result-queries/) - Stored procedures
- [10-attribute-based-tables](examples/10-attribute-based-tables/) - PHP 8 attributes
- [11-repository-pattern](examples/11-repository-pattern/) - Repository pattern
- [12-clean-architecture](examples/12-clean-architecture/) - Domain separation
- [13-pagination](examples/13-pagination/) - Pagination techniques
- [14-active-record-model](examples/14-active-record-model/) - Active Record pattern

###  Health Score

55

—

FairBetter than 97% of packages

Maintenance85

Actively maintained with recent releases

Popularity30

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity78

Established project with proven stability

 Bus Factor1

Top contributor holds 99.2% 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 ~25 days

Recently: every ~34 days

Total

75

Last Release

88d ago

Major Versions

0.10.0 → 1.0.02025-09-23

1.2.0 → 2.0.02026-01-06

### Community

Maintainers

![](https://www.gravatar.com/avatar/4c25e43acaa22b4fb758a710b69c2ab75947a6642925e3bec9c98196b1f2a433?d=identicon)[usernane](/maintainers/usernane)

---

Top Contributors

[![usernane](https://avatars.githubusercontent.com/u/12120015?v=4)](https://github.com/usernane "usernane (1073 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (9 commits)")

---

Tags

databasehacktoberfestmysqlphpwebfiori-frameworkphpdatabaselibrarymysqlquery builder

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

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

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

###  Alternatives

[clouddueling/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

1.3k22.9k](/packages/clouddueling-mysqldump-php)[stefangabos/zebra_database

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

11812.0k](/packages/stefangabos-zebra-database)[soosyze/queryflatfile

The Queryflatfile is PHP library for simple database not SQL

181.0k1](/packages/soosyze-queryflatfile)

PHPackages © 2026

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