PHPackages                             flatphp/lightdb - 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. flatphp/lightdb

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

flatphp/lightdb
===============

simple light db component

v5.2.0(5y ago)5321MITPHPPHP &gt;=5.5

Since Nov 11Pushed 5y ago1 watchersCompare

[ Source](https://github.com/flatphp/lightdb)[ Packagist](https://packagist.org/packages/flatphp/lightdb)[ RSS](/packages/flatphp-lightdb/feed)WikiDiscussions master Synced 6d ago

READMEChangelogDependenciesVersions (15)Used By (1)

Lightdb
=======

[](#lightdb)

Lightdb is a simple db component. 轻量DB库

Install 安装
==========

[](#install-安装)

```
composer require flatphp/lightdb

```

Usage 使用
========

[](#usage-使用)

```
use \Lightdb\DB;

// config 配置
$conf = array(
    'dsn' => 'mysql:host=localhost;dbname=testdb',
    'username' => 'root',
    'password' => '123456',
    'options' => [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8']
);

// init 初始化
DB::init($conf);

// raw sql 原生sql使用
$sql = 'select * from test where id>?';

// static use 静态门面模式使用
$data = DB::fetchAllIndexed($sql, 2);

$sql = 'insert into test(aa, bb) values(?, ?)';
$res = DB::execute($sql, [1, 2]);

// connection instance use
$conn = DB::conn();
$sql = 'select * from channel where id>?';
$data = $conn->fetchAll($sql, 2);

// fetch all to classes array
// 数据实例化对象
$data = $conn->fetchAllTo('MyModel', $sql, 2);

// fetch row to class
$data = $conn->fetchRowTo('MyModel', $sql, 2);
```

Support Fetch Method
====================

[](#support-fetch-method)

methodintrofetchAllfetch all array with assoc, empty array returned if nothing or falsefetchAllIndexedfetch all with first field as indexed key, empty array returned if nothing or falsefetchAllGroupedfetch all grouped array with first field as keys, empty array returned if nothing or falsefetchRowfetch one row array with assoc, false is returned if failurefetchColumnfetch first column array, empty array returned if nothing or falsefetchColumnGroupedfetch grouped column array with first field as keys of grouped array, empty array returned if nothing or falsefetchPairsfetch pairs of first column as Key and second column as Value, empty array returned if nothing or falsefetchPairsGroupedfetch grouped pairs of K/V with first field as keys of grouped array, empty array returned if nothing of falsefetchOnefetch one field value, false returned if nothing or falsefetchAllTofetch all to classes array, empty array returned if nothing or falsefetchAllIndexedTofetch all to classes array with firest field as indexed key, empty array returned if nothing or falsefetchAllGroupedTofetch all grouped array with first field as keys, empty array returned if nothing or falsefetchRowTofetch one row to class, false is returned if failureMaster-Slaves 主从使用
==================

[](#master-slaves-主从使用)

```
use \Lightdb\DB;

$conf = array(
    'dsn' => 'mysql:host=master;dbname=testdb',
    'username' => 'root',
    'password' => '123456',
    'options' => [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'],
    'slaves' => array(
        [
            'dsn' => 'mysql:host=slave1;dbname=testdb',
            'username' => 'root',
            'password' => '123456',
        ],
        [
            'dsn' => 'mysql:host=slave2;dbname=testdb',
            'username' => 'root',
            'password' => '123456',
        ]
    )
);

DB::init($conf);

// write to master db
$sql = 'insert into test(aa) values(1)';
$res = DB::execute($sql);

// select from slave db
$sql = 'select * from test';
$data = DB::fetchAll($sql);

// force read from master
// 强制从主库读取
$sql = 'select * from test';
$data = DB::master()->fetchAll($sql);
```

Multiple DB Instance 多DB实例
==========================

[](#multiple-db-instance-多db实例)

```
use \Lightdb\DB;

$conf = array(
    'db1' => array(...),
    'db2' => array(...),
);

$sql = 'select * from test';
DB::conn('db1')->fetchRow($sql);
DB::conn('db2')->fetchPairs($sql);
```

Transaction 事务
==============

[](#transaction-事务)

```
use \Lightdb\DB;

$transaction = DB::transaction();
$transaction->run(function(){
    // do something
}, function(){
    // do something after commit
}, function(){
    // do something after rollback
});
```

another way:

```
use \Lightdb\DB;
$transaction = DB::transaction();
$transaction->beginTransaction();
try {
    // do something
    $transaction->commit();
} catch (\Exception $e) {
    $transaction->rollback();
    throw $e;
}
```

Query Builder sql构建查询
=====================

[](#query-builder-sql构建查询)

Select
------

[](#select)

```
use Lightdb\DB;

$conn = DB::conn();

$conn->query()->table('users')->select('name, age')->where('age>?', 10)->fetchRow();

// read from master
$query = DB::query(['master' => true])->table('users as u')->select('u.id, u.name')
    ->leftJoin('score as s', 'u.user_id=s.user_id')
    ->where('class=?', 1)->orWhere('(age>12 AND sex=1)')
    ->orderBy('u.id DESC');
$result = $query->page(1, 10)->fetchAll();
$count = $query->count();
```

Insert
------

[](#insert)

```
use Lightdb\DB;

DB::query()->table('users')->insert(array(
    'name' => 'peter',
    'age' => 12,
    'sex' => 1
));
```

Update
------

[](#update)

```
use Lightdb\DB;
use Lightdb\Raw;

DB::conn('other')->query()->table('users')->whereIn('name', ['peter', 'tom'])->update(array(
    'class' => 1,
    'point' => new Raw('point+1')
));
```

Delete
------

[](#delete)

```
use Lightdb\DB;

// get delete sql
DB::query()->where('id=?', 10)->delete();

// execute
$query = DB::conn('another')->query();
$query->table('users')->whereNotIn('id', [1,2,3])->delete();
print_r($query->getLog());
```

#### Query Join Method

[](#query-join-method)

- leftJoin($table, $on, $bind = null)
- rightJoin($table, $on, $bind = null)
- innerJoin($table, $on, $bind = null)
- fullJoin($table, $on, $bind = null)

#### Query Where Method

[](#query-where-method)

- where($where, $bind = null)
- whereIn($field, array $values)
- whereNotIn($field, array $values)
- orWhere($where, $bind = null)
- orWhereIn($field, array $values)
- orWhereNotIn($field, array $values)

#### Query Limit and Offset

[](#query-limit-and-offset)

- limit($limit, $offset = 0)
- offset($offset)
- page($page, $page\_size = 10)

#### Query Count

[](#query-count)

- count() (ignore limit and offset)

#### Execute

[](#execute)

- insert(array $data)
- update(array $data)
- delete()

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity60

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

Recently: every ~71 days

Total

14

Last Release

1874d ago

Major Versions

v1.0.0 → v2.0.02019-11-13

v2.0.0 → v3.0.02019-12-22

v3.2.0 → v4.0.02020-01-12

v4.2.0 → v5.0.02020-02-28

### Community

Maintainers

![](https://www.gravatar.com/avatar/e3e4d193838370dbe5119947cb84acd917f9e7dd4baf5ed9d0dbc88f26310fa5?d=identicon)[fredyang](/maintainers/fredyang)

---

Top Contributors

[![shukyoo](https://avatars.githubusercontent.com/u/2231396?v=4)](https://github.com/shukyoo "shukyoo (21 commits)")

---

Tags

databaselightdb

### Embed Badge

![Health badge](/badges/flatphp-lightdb/health.svg)

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

###  Alternatives

[doctrine/dbal

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

9.7k578.4M5.6k](/packages/doctrine-dbal)[doctrine/orm

Object-Relational-Mapper for PHP

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

Symfony DoctrineBundle

4.8k241.3M3.3k](/packages/doctrine-doctrine-bundle)[doctrine/migrations

PHP Doctrine Migrations project offer additional functionality on top of the database abstraction layer (DBAL) for versioning your database schema and easily deploying changes to it. It is a very easy to use and a powerful tool.

4.8k204.8M440](/packages/doctrine-migrations)[doctrine/data-fixtures

Data Fixtures for all Doctrine Object Managers

2.9k136.1M516](/packages/doctrine-data-fixtures)[robmorgan/phinx

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

4.5k46.2M405](/packages/robmorgan-phinx)

PHPackages © 2026

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