PHPackages                             romagny13/micro-db - 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. romagny13/micro-db

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

romagny13/micro-db
==================

MicroPHP DB library

0.0.2(9y ago)022MITPHP

Since May 5Pushed 9y ago1 watchersCompare

[ Source](https://github.com/romagny13/micro-db)[ Packagist](https://packagist.org/packages/romagny13/micro-db)[ RSS](/packages/romagny13-micro-db/feed)WikiDiscussions master Synced yesterday

READMEChangelog (2)Dependencies (1)Versions (3)Used By (0)

Micro Db
========

[](#micro-db)

- [MicroPHP](https://github.com/romagny13/micro-php)

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

[](#installation)

```
composer require romagny13/micro-db

```

Usage
-----

[](#usage)

Configure the database connection.
----------------------------------

[](#configure-the-database-connection)

Example:

```
$settings = [
    'dsn' =>"mysql:host=localhost;dbname=blog",
    'username'=>'root',
    'password' =>''
];
Db::setConnectionStringSettings($settings['dsn'],$settings['username'],$settings['password']);
```

Sql tables/columns Strategy
---------------------------

[](#sql-tablescolumns-strategy)

By default the columns are wrapped with back ticks

Example:

```
select `posts`.`id`,`title`,`content`,`users`.`id`,`users`.`username` from `posts`,`users` order by `title`
```

Change the strategy. Example:

```
Db::setTableAndColumnStrategy('[',']');
```

```
select [posts].[id],[title],[content],[users].[id],[users].[username] from [posts],[users] order by [title]
```

With the Query Builder:
-----------------------

[](#with-the-query-builder)

- select
- insert\_into
- update
- delete

Examples:

### Select

[](#select)

```
$posts = Db::getInstance()
    ->select('id','title','content','user_id')
    ->from('posts')
    ->where(Condition::op('user_id',1))
    ->orderBy('title')
    ->limit(10)
    ->fetchAll();
```

Other example, fetch a class

```
class Post { }

$posts = Db::getInstance()
    ->select('posts.id','title','content','user_id','users.id','users.username')
    ->from('posts','users')
    ->where('user_id=1')
    ->orderBy(Sort::desc('title'),'content desc')
    ->limit(2,10)
    ->fetchAll(Post::class);
```

Get the querystring :

```
$queryString = Db::getInstance()->select('posts.id','title','content','user_id','users.id','users.username')
    ->from('posts','users')
    ->where('user_id=1')
    ->orderBy(Sort::desc('title'),'content desc')
    ->limit(2,10)
    ->build();

var_dump($queryString);
```

```
select `posts`.`id`,`title`,`content`,`user_id`,`users`.`id`,`users`.`username` from `posts`,`users` where user_id=1 order by `title` desc,`content` desc limit 2,10
```

Insert
------

[](#insert)

```
$success = Db::getInstance()
    ->insert_into('posts')
    ->columns('title','content','user_id')
    ->execute(['my title','my content',1]);
```

Or

```
$success = Db::getInstance()
    ->insert_into('posts')
    ->columns('title','content','user_id')
    ->values('my title','my content',1)
    ->execute();
```

and get the last inserted id

```
$id = Db::getInstance()->lastInsertId();
```

Update
------

[](#update)

```
$success = Db::getInstance()
    ->update('posts')
    ->set([
        'title'=>'new title',
        'content' => 'new content'
    ])
    ->where(Condition::op('id',1))
    ->execute();
```

Delete
------

[](#delete)

```
$success = Db::getInstance()
    ->delete_from('posts')
    ->where(Condition::op('id',1))
    ->execute();
```

### Condition helper

[](#condition-helper)

- op
- in
- between
- like

plus chaining conditions with:

- *and*
- *or*

PDO
---

[](#pdo)

Simple query

```
$posts = Db::getInstance()
    ->query('select * from posts')
    ->fetchAllWithClass(Post::class);
```

Query with params

```
$posts = Db::getInstance()
    ->prepare('select * from posts where id=:id')
    ->setParam(':id',1)
    ->fetchObject(Post::class);
```

Other example

```
$success = Db::getInstance()
    ->prepare('insert into posts (title,content,user_id) values (?,?,?)')
    ->execute(['My title', 'My content',2]);

$id = Db::getInstance()->lastInsertId();
```

Or with named params

```
$success = Db::getInstance()
    ->prepare('insert into posts (title,content,user_id) values (:title,:content,:user_id)')
    ->setParam(':title','My title')
    ->setParam(':content','My content')
    ->setParam(':user_id',2)
    ->execute();

$id = Db::getInstance()->lastInsertId();
```

Model
-----

[](#model)

Create a model and define the db table. By default all columns will be filled \['\*'\].

```
use \MicroPHP\Db\Model;

class PostModel extends Model
{
    public function __construct()
    {
        $this->table = 'posts';
    }
}
```

Define the columns to fill

```
use \MicroPHP\Db\Model;

class PostModel extends Model
{
    public function __construct()
    {
        $this->table = 'posts';
        $this->columns = ['id','title','content','user_id'];
    }
}
```

### All

[](#all)

get all the records of the table

```
$posts = PostModel::all();
```

With limit

Example: only 10 posts (maximum) will be returned

```
$posts = PostModel::all(10);
```

With offset + limit

Example: only 10 posts (maximum) will be returned after 2 posts

```
$posts = PostModel::all(2,10);
```

### Where

[](#where)

Allow to select the records to return (array)

```
$posts = PostModel::where(Condition::op('user_id',1)->_or_(Condition::op('user_id',2)));
```

or with a string

```
$posts = PostModel::where('user_id=1 or user_id=2');
```

With offset + limit

```
$posts = PostModel::where('user_id=1 or user_id=2',2,10);
```

### Find

[](#find)

Returns only one item.

```
$post = PostModel::find(Condition::op('id',1));
```

### Create

[](#create)

Example:

```
$success = PostModel::create([
    'title' => 'My title',
    'content' => 'My content',
    'user_id' => 1
]);
```

### Update

[](#update-1)

Example:

```
$success = PostModel::update([
    'title' => 'My new title',
    'content' => 'My new content'
],Condition::op('id',1));
```

### Delete

[](#delete-1)

Example:

```
$success = PostModel::delete(Condition::op('id',1));
```

### Query and prepare

[](#query-and-prepare)

Are shortcuts to Db functions.

### Relations

[](#relations)

Add relations (0-1) or (1-1) to other models

```
class UserModel extends Model
{
    public function __construct()
    {
        $this->table = 'users';
    }
}

class CategoryModel extends Model
{
    public function __construct()
    {
        $this->table = 'categories';
    }
}

class PostModel extends Model
{
    public function __construct()
    {
        $this->table = 'posts';
        $this->columns = ['title','content'];

        // relations
        $this->addRelation('users',['user_id' => 'id'],UserModel::class, 'user');
        $this->addRelation('categories',['category_id' => 'id'],CategoryModel::class, 'category');
    }
}
```

addRelation parameters:

- foreign key table name
- foreign key =&gt; primary key pairs
- model to fill
- property name to add

User and category properties will be added to the post model.

Example:

```
$post = PostModel::find(Condition::op('id',1));
```

###  Health Score

24

—

LowBetter than 31% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

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

Total

2

Last Release

3342d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7684350?v=4)[romagny13](/maintainers/romagny13)[@romagny13](https://github.com/romagny13)

---

Top Contributors

[![romagny13](https://avatars.githubusercontent.com/u/7684350?v=4)](https://github.com/romagny13 "romagny13 (2 commits)")

---

Tags

microdbmicrophp

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/romagny13-micro-db/health.svg)

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

###  Alternatives

[robmorgan/phinx

Phinx makes it ridiculously easy to manage the database migrations for your PHP app.

4.6k48.7M443](/packages/robmorgan-phinx)[spatie/laravel-translation-loader

Store your language lines in the database, yaml or other sources

8453.1M63](/packages/spatie-laravel-translation-loader)[aura/sqlquery

Object-oriented query builders for MySQL, Postgres, SQLite, and SQLServer; can be used with any database connection library.

4563.1M37](/packages/aura-sqlquery)[laminas/laminas-db

Database abstraction layer, SQL abstraction, result set abstraction, and RowDataGateway and TableDataGateway implementations

14223.5M228](/packages/laminas-laminas-db)[envms/fluentpdo

FluentPDO is a quick and light PHP library for rapid query building. It features a smart join builder, which automatically creates table joins.

921530.0k13](/packages/envms-fluentpdo)[danielme85/laravel-log-to-db

Custom Laravel Log channel handler that can store log events to SQL or MongoDB databases. Uses Laravel native logging functionality.

134979.2k1](/packages/danielme85-laravel-log-to-db)

PHPackages © 2026

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