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

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

initphp/database
================

InitPHP DataBase (QueryBuilder, DBAL and ORM) Library

3.0(2y ago)6242[2 issues](https://github.com/InitPHP/Database/issues)MITPHPPHP &gt;=8.0

Since Aug 20Pushed 2y ago1 watchersCompare

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

READMEChangelog (10)Dependencies (2)Versions (24)Used By (0)

InitPHP Database
================

[](#initphp-database)

Manage your database with or without abstraction. This library is built on the PHP PDO plugin and is mainly used to build and execute SQL queries.

[![Latest Stable Version](https://camo.githubusercontent.com/baed3c2920c05447fc5ea6a370a5ce98b042579fa2f6ad752151becaf5a086c7/687474703a2f2f706f7365722e707567782e6f72672f696e69747068702f64617461626173652f76)](https://packagist.org/packages/initphp/database) [![Total Downloads](https://camo.githubusercontent.com/2df44ef0586720e242a2ecda8ef9ac5f18021202848be571988b559c9c246dfe/687474703a2f2f706f7365722e707567782e6f72672f696e69747068702f64617461626173652f646f776e6c6f616473)](https://packagist.org/packages/initphp/database) [![Latest Unstable Version](https://camo.githubusercontent.com/b3ee68aa13e716cb973d7ce16de8aa2764c0d6eb381bbe3b1c6a73c77a73e837/687474703a2f2f706f7365722e707567782e6f72672f696e69747068702f64617461626173652f762f756e737461626c65)](https://packagist.org/packages/initphp/database) [![License](https://camo.githubusercontent.com/73b3222ba225d30ddadf704342e57eaf2a40f5275a552da767215d66c09e139c/687474703a2f2f706f7365722e707567782e6f72672f696e69747068702f64617461626173652f6c6963656e7365)](https://packagist.org/packages/initphp/database) [![PHP Version Require](https://camo.githubusercontent.com/e6ec0dc78eb55b24b255019166a424a45644e515bda3ed8b393d551c93742bdb/687474703a2f2f706f7365722e707567782e6f72672f696e69747068702f64617461626173652f726571756972652f706870)](https://packagist.org/packages/initphp/database)

Requirements
------------

[](#requirements)

- PHP 8.0 and later.
- PHP PDO extension.

Supported Databases
-------------------

[](#supported-databases)

This library should work correctly in almost any database that uses basic SQL syntax. Databases supported by PDO and suitable drivers are available at .

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

[](#installation)

```
composer require initphp/database

```

Usage
-----

[](#usage)

### QueryBuilder &amp; DBAL and CRUD

[](#querybuilder--dbal-and-crud)

```
require_once "vendor/autoload.php";
use \InitPHP\Database\DB;

// Connection
DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8mb4',
    'collation' => 'utf8mb4_general_ci',
]);
```

#### Create

[](#create)

```
use \InitPHP\Database\DB;
$data = [
    'title'     => 'Post Title',
    'content'   => 'Post Content',
];

$isInsert = DB::create('post', $data);

/**
* This executes the following query.
*
* INSERT INTO post
* (title, content)
* VALUES
* ("Post Title", "Post Content");
*/
if($isInsert){
    // Success
}
```

##### Create Batch

[](#create-batch)

```
use \InitPHP\Database\DB;

$data = [
    [
        'title'     => 'Post Title 1',
        'content'   => 'Post Content 1',
        'author'    => 5
    ],
    [
        'title'     => 'Post Title 2',
        'content'   => 'Post Content 2'
    ],
];

$isInsert = DB::createBatch('post', $data);

/**
* This executes the following query.
*
* INSERT INTO post
* (title, content, author)
* VALUES
* ("Post Title 1", "Post Content 1", 5),
* ("Post Title 2", "Post Content 2", NULL);
*/

if($isInsert){
    // Success
}
```

#### Read

[](#read)

```
use \InitPHP\Database\DB;

/**
* This executes the following query.
*
* SELECT user.name AS author_name, post.id, post.title
* FROM post, user
* WHERE user.id = post.author AND post.status = 1
* ORDER BY post ASC, post.created_at DESC
* LIMIT 20, 10
*/

/** @var \InitORM\DBAL\DataMapper\Interfaces\DataMapperInterface $res */
$res = DB::select('user.name as author_name', 'post.id', 'post.title')
    ->from('post')
    ->selfJoin('user', 'user.id=post.author')
    ->where('post.status', 1)
    ->orderBy('post.id', 'ASC')
    ->orderBy('post.created_at', 'DESC')
    ->offset(20)->limit(10)
    ->read();

if($res->numRows() > 0){
    $results = $res->asAssoc()
                    ->rows();
    foreach ($results as $row) {
        echo $row['title'] . ' by ' . $row['author_name'] . '';
    }
}
```

#### Update

[](#update)

```
use \InitPHP\Database\DB;
$data = [
    'title'     => 'New Title',
    'content'   => 'New Content',
];

$isUpdate = DB::where('id', 13)
                ->update('post', $data);

/**
* This executes the following query.
*
* UPDATE post
* SET title = "New Title", content = "New Content"
* WHERE id = 13
*/
if ($isUpdate) {
    // Success
}
```

##### Update Batch

[](#update-batch)

```
use \InitPHP\Database\DB;
$data = [
    [
        'id'        => 5,
        'title'     => 'New Title #5',
        'content'   => 'New Content #5',
    ],
    [
        'id'        => 10,
        'title'     => 'New Title #10',
    ]
];

$isUpdate = DB::where('status', '!=', 0)
                ->updateBatch('id', 'post', $data);

/**
* This executes the following query.
*
* UPDATE post SET
* 	title = CASE
* 		WHEN id = 5 THEN 'New Title #5'
* 		WHEN id = 10 THEN 'New Title #10'
* 		ELSE title END,
* 	content = CASE
* 		WHEN id = 5 THEN 'New Content #5'
* 		ELSE content END
* WHERE status != 0 AND id IN (5, 10)
*/
if ($isUpdate) {
    // Success
}
```

#### Delete

[](#delete)

```
use \InitPHP\Database\DB;

$isDelete = DB::where('id', 13)
                ->delete('post');

/**
* This executes the following query.
*
* DELETE FROM post WHERE id = 13
*/
if ($isUpdate) {
    // Success
}
```

### RAW

[](#raw)

```
use \InitPHP\Database\DB;

/** @var \InitORM\DBAL\DataMapper\Interfaces\DataMapperInterface $res */
$res = DB::query("SELECT id FROM post WHERE user_id = :id", [
    ':id'   => 5
]);
```

#### Builder for RAW

[](#builder-for-raw)

```
use \InitPHP\Database\DB;

/** @var \InitORM\DBAL\DataMapper\Interfaces\DataMapperInterface $res */
$res = DB::select(DB::raw("CONCAT(name, ' ', surname) AS fullname"))
        ->where(DB::raw("title = '' AND (status = 1 OR status = 0)"))
        ->limit(5)
        ->read('users');

/**
 * SELECT CONCAT(name, ' ', surname) AS fullname
 * FROM users
 * WHERE title = '' AND (status = 1 OR status = 0)
 * LIMIT 5
 */
$results = $res->asAssoc()
                ->rows();
foreach ($results as $row) {
    echo $row['fullname'];
}
```

#### Working With A Different Connection

[](#working-with-a-different-connection)

This library was developed with the thought that you would work with a single database and connection, but I know that in some projects you work with more than one connection and database.

If you want to work with a different non-global connection, use the `connect()` method.

```
use \InitPHP\Database\DB;

DB::connect([
    'dsn'       => 'mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8mb4',
    'collation' => 'utf8mb4_general_ci',
]);
```

### Model and Entity

[](#model-and-entity)

Model and Entity; are two common concepts used in database abstraction. To explain these two concepts in the roughest way;

- **Model :** Each model is a class that represents a table in the database.
- **Entity :** Entity is a class that represents a single row of data.

The most basic example of a model class would look like this.

```
namespace App\Model;

class Posts extends \InitPHP\Database\Model
{

    /**
    * If your model will use a connection other than your global connection, provide connection information.
    * @var array|null Default : NULL
    */
    protected array $credentials = [
        'dsn'               => '',
        'username'          => 'root',
        'password'          => '',
        'charset'           => 'utf8mb4',
        'collation'         => 'utf8mb4_unicode_ci',
    ];

    /**
     * If not specified, \InitPHP\Database\Entity::class is used by default.
     *
     * @var string
     */
    protected $entity = \App\Entities\PostEntity::class;

    /**
     * If not specified, the name of your model class is used.
     *
     * @var string
     */
    protected string $schema = 'posts';

    /**
     * The name of the PRIMARY KEY column. If not, define it as NULL.
     *
     * @var string
     */
    protected string $schemaId = 'id';

    /**
     * Specify FALSE if you want the data to be permanently deleted.
     *
     * @var bool
     */
    protected bool $useSoftDeletes = true;

    /**
     * Column name to hold the creation time of the data.
     *
     * @var string|null
     */
    protected ?string $createdField = 'created_at';

    /**
     * The column name to hold the last time the data was updated.
     *
     * @var string|null
     */
    protected ?string $updatedField = 'updated_at';

    /**
     * Column name to keep deletion time if $useSoftDeletes is active.
     *
     * @var string|null
     */
    protected ?string $deletedField = 'deleted_at';

    protected bool $readable = true;

    protected bool $writable = true;

    protected bool $deletable = true;

    protected bool $updatable = true;

}
```

The most basic example of a entity class would look like this.

```
namespace App\Entities;

class PostEntity extends \InitPHP\Database\Entity
{
    /**
     * An example of a getter method for the "post_title" column.
     *
     * Usage :
     * echo $entity->post_title;
     */
    public function getPostTitleAttribute($title)
    {
        return strtoupper($title);
    }

    /**
     * An example of a setter method for the "post_title" column.
     *
     * Usage :
     * $entity->post_title = 'New Post Title';
     */
    public function setPostTitleAttribute($title)
    {
        $this->post_title = strtolower($title);
    }

}
```

Development Tools
-----------------

[](#development-tools)

Below I have mentioned some developer tools that you can use during and after development.

### Logger

[](#logger)

```
use \InitPHP\Database\DB;

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',

    'log'       => __DIR__ '/logs/db.log', // string, callable or object
]);
```

If you define a file path as a String; Attempts are made to write into it with `file_put_contents()`.

*Note :* You can define variables such as `{year}`, `{month}`, `{day}` in the filename.

- You can also define an object with the `critical` method. The database library will pass the log message to this method as a parameter. Or define it as callable array to use any method of the object.

```
use \InitPHP\Database\DB;

class Logger {

    public function critical(string $msg)
    {
        $path = __DIR__ . '/log.log';
        file_put_contents($path, $msg, FILE_APPEND);
    }

}

$logger = new Logger();

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',

    'log'       => $logger, // or [$logger, 'critical']
]);
```

- Similarly it is possible to define it in a callable method.

```
use \InitPHP\Database\DB;

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',

    'log'       => function (string $msg) {
        $path = __DIR__ . '/log.log';
        file_put_contents($path, $msg, FILE_APPEND);
    },
]);
```

### DeBug Mode

[](#debug-mode)

Debug mode is used to include the executed SQL statement in the error message. ***It should only be activated in the development environment***.

```
use \InitPHP\Database\DB;

DB::createImmutable([
    'dsn'       => 'mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4;',
    'username'  => 'root',
    'password'  => '',

    'debug'     => true, // boolean
]);
```

### Profiler Mode

[](#profiler-mode)

Profiler mode is a developer tool available in v3 and above. It is a feature that allows you to see the executed queries along with their execution times.

```
use InitPHP\Database\DB;

DB::enableQueryLog();

DB::table('users')->where('name', 'John')->read();

var_dump(DB::getQueryLogs());

/**
 * The output of the above example looks like this;
 * [
 *      [
 *          'query' => 'SELECT * FROM users WHERE name = :name',
 *          'time'  => '0.00064',
 *          'args'  => [
 *              ':name'     => 'John',
 *          ]
 *      ]
 * ]
 *
 */
```

To Do
-----

[](#to-do)

- A more detailed documentation will be prepared.

Getting Help
------------

[](#getting-help)

If you have questions, concerns, bug reports, etc, please file an issue in this repository's Issue Tracker.

Getting Involved
----------------

[](#getting-involved)

> All contributions to this project will be published under the MIT License. By submitting a pull request or filing a bug, issue, or feature request, you are agreeing to comply with this waiver of copyright interest.

There are two primary ways to help:

- Using the issue tracker, and
- Changing the code-base.

### Using the issue tracker

[](#using-the-issue-tracker)

Use the issue tracker to suggest feature requests, report bugs, and ask questions. This is also a great way to connect with the developers of the project as well as others who are interested in this solution.

Use the issue tracker to find ways to contribute. Find a bug or a feature, mention in the issue that you will take on that effort, then follow the Changing the code-base guidance below.

### Changing the code-base

[](#changing-the-code-base)

Generally speaking, you should fork this repository, make changes in your own fork, and then submit a pull request. All new code should have associated unit tests that validate implemented features and the presence or lack of defects. Additionally, the code should follow any stylistic and architectural guidelines prescribed by the project. In the absence of such guidelines, mimic the styles and patterns in the existing code-base.

Credits
-------

[](#credits)

- [Muhammet ŞAFAK](https://www.muhammetsafak.com.tr) &lt;&gt;

License
-------

[](#license)

Copyright © 2022 [MIT License](./LICENSE)

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance13

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity62

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

Recently: every ~33 days

Total

23

Last Release

891d ago

Major Versions

v1.1.x-dev → 2.02022-10-16

v2.2.x-dev → 3.02023-12-09

PHP version history (2 changes)1.1.13PHP &gt;=7.4

3.0PHP &gt;=8.0

### Community

Maintainers

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

---

Top Contributors

[![muhammetsafak](https://avatars.githubusercontent.com/u/104234499?v=4)](https://github.com/muhammetsafak "muhammetsafak (100 commits)")

---

Tags

data-mapperdatabasedb-entity-classdb-modeldbalormphpphp-pdophp-pdo-mysqlphp-pdo-sqlitephp7query-buildersqlsql-query-builder

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90440.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)[wildside/userstamps

Laravel Userstamps provides an Eloquent trait which automatically maintains `created\_by` and `updated\_by` columns on your model, populated by the currently authenticated user in your application.

7511.7M13](/packages/wildside-userstamps)

PHPackages © 2026

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