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

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

mix/database
============

Simple database for use in multiple execution environments, with support for FPM, Swoole, Workerman, and optional pools

v3.0.23(3y ago)1515.3k↓50%8[1 issues](https://github.com/mix-php/database/issues)9Apache-2.0PHPPHP &gt;=7.2.0CI failing

Since Dec 27Pushed 6mo ago1 watchersCompare

[ Source](https://github.com/mix-php/database)[ Packagist](https://packagist.org/packages/mix/database)[ Docs](https://openmix.org/mix-php)[ RSS](/packages/mix-database/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (2)Versions (62)Used By (9)

> OpenMix 出品：[https://openmix.org](https://openmix.org/mix-php)

Mix Database
============

[](#mix-database)

Simple database for use in multiple execution environments, with support for FPM, CLI, Swoole, WorkerMan, and optional connection pool (coroutine)

可在各种环境中使用的轻量数据库，支持 FPM、CLI、Swoole、WorkerMan，可选的连接池 (协程)

技术交流
----

[](#技术交流)

知乎：
官方QQ群：[284806582](https://shang.qq.com/wpa/qunwpa?idkey=b3a8618d3977cda4fed2363a666b081a31d89e3d31ab164497f53b72cf49968a), [825122875](http://shang.qq.com/wpa/qunwpa?idkey=d2908b0c7095fc7ec63a2391fa4b39a8c5cb16952f6cfc3f2ce4c9726edeaf20)敲门暗号：db

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

[](#installation)

```
composer require mix/database

```

Quick start
-----------

[](#quick-start)

注意：[协程环境中，不可在并发请求中使用单例](https://openmix.org/mix-php/docs/3.0/#/zh-cn/instructions?id=%e5%8d%8f%e7%a8%8b%e5%8d%95%e4%be%8b%e5%ae%9e%e4%be%8b%e5%8c%96)

```
$db = new Mix\Database\Database('mysql:host=127.0.0.1;port=3306;charset=utf8;dbname=test', 'username', 'password');
```

创建

```
$db->insert('users', [
    'name' => 'foo',
    'balance' => 0,
]);
```

查询

```
$db->table('users')->where('id = ?', 1)->first();
```

更新

```
$db->table('users')->where('id = ?', 1)->update('name', 'foo1');
```

删除

```
$db->table('users')->where('id = ?', 1)->delete();
```

启动连接池 Pool
----------

[](#启动连接池-pool)

在 `Swoole` 协程环境中，启动连接池

```
$maxOpen = 50;        // 最大开启连接数
$maxIdle = 20;        // 最大闲置连接数
$maxLifetime = 3600;  // 连接的最长生命周期
$waitTimeout = 0.0;   // 从池获取连接等待的时间, 0为一直等待
$db->startPool($maxOpen, $maxIdle, $maxLifetime, $waitTimeout);
Swoole\Runtime::enableCoroutine(); // 必须放到最后，防止触发协程调度导致异常
```

连接池统计

```
$db->poolStats(); // array, fields: total, idle, active
```

创建 Insert
---------

[](#创建-insert)

创建

```
$data = [
    'name' => 'foo',
    'balance' => 0,
];
$db->insert('users', $data);
```

获取 InsertId

```
$data = [
    'name' => 'foo',
    'balance' => 0,
];
$insertId = $db->insert('users', $data)->lastInsertId();
```

替换创建

```
$data = [
    'name' => 'foo',
    'balance' => 0,
];
$db->insert('users', $data, 'REPLACE INTO');
```

批量创建

```
$data = [
    [
        'name' => 'foo',
        'balance' => 0,
    ],
    [
        'name' => 'foo1',
        'balance' => 0,
    ]
];
$db->batchInsert('users', $data);
```

使用函数创建

```
$data = [
    'name' => 'foo',
    'balance' => 0,
    'add_time' => new Mix\Database\Expr('CURRENT_TIMESTAMP()'),
];
$db->insert('users', $data);
```

查询 Select
---------

[](#查询-select)

### 获取结果

[](#获取结果)

方法名称描述get(): array获取多行first(): array or object获取第一行value(string $field): mixed获取第一行某个字段statement(): \\PDOStatement获取原始结果集### Where

[](#where)

#### AND

[](#and)

```
$db->table('users')->where('id = ? AND name = ?', 1, 'foo')->get();
```

```
$db->table('users')->where('id = ?', 1)->where('name = ?', 'foo')->get();
```

#### OR

[](#or)

```
$db->table('users')->where('id = ? OR id = ?', 1, 2)->get();
```

```
$db->table('users')->where('id = ?', 1)->or('id = ?', 2)->get();
```

#### IN

[](#in)

```
$db->table('users')->where('id IN (?)', [1, 2])->get();
```

```
$db->table('users')->where('id NOT IN (?)', [1, 2])->get();
```

### Select

[](#select)

```
$db->table('users')->select('id, name')->get();
```

```
$db->table('users')->select('id', 'name')->get();
```

```
$db->table('users')->select('name AS n')->get();
```

### Order

[](#order)

```
$db->table('users')->order('id', 'desc')->get();
```

```
$db->table('users')->order('id', 'desc')->order('name', 'asc')->get();
```

### Limit

[](#limit)

```
$db->table('users')->limit(5)->get();
```

```
$db->table('users')->offset(10)->limit(5)->get();
```

### Group &amp; Having

[](#group--having)

```
$db->table('news')->select('uid, COUNT(*) AS total')->group('uid')->having('COUNT(*) > ?', 0)->get();
```

```
$db->table('news')->select('uid, COUNT(*) AS total')->group('uid')->having('COUNT(*) > ? AND COUNT(*) < ?', 0, 10)->get();
```

### Join

[](#join)

```
$db->table('news AS n')->select('n.*, u.name')->join('users AS u', 'n.uid = u.id')->get();
```

```
$db->table('news AS n')->select('n.*, u.name')->leftJoin('users AS u', 'n.uid = u.id AND u.balance > ?', 10)->get();
```

更新 Update
---------

[](#更新-update)

更新单个字段

```
$db->table('users')->where('id = ?', 1)->update('name', 'foo1');
```

获取影响行数

```
$rowsAffected = $db->table('users')->where('id = ?', 1)->update('name', 'foo1')->rowCount();
```

更新多个字段

```
$data = [
    'name' => 'foo1',
    'balance' => 100,
];
$db->table('users')->where('id = ?', 1)->updates($data);
```

使用表达式更新

```
$db->table('users')->where('id = ?', 1)->update('balance', new Mix\Database\Expr('balance + ?', 1));
```

```
$data = [
    'balance' => new Mix\Database\Expr('balance + ?', 1),
];
$db->table('users')->where('id = ?', 1)->updates($data);
```

使用函数更新

```
$db->table('users')->where('id = ?', 1)->update('add_time', new Mix\Database\Expr('CURRENT_TIMESTAMP()'));
```

```
$data = [
    'add_time' => new Mix\Database\Expr('CURRENT_TIMESTAMP()'),
];
$db->table('users')->where('id = ?', 1)->updates($data);
```

删除 Delete
---------

[](#删除-delete)

删除

```
$db->table('users')->where('id = ?', 1)->delete();
```

获取影响行数

```
$rowsAffected = $db->table('users')->where('id = ?', 1)->delete()->rowCount();
```

原生 Raw
------

[](#原生-raw)

```
$db->raw('SELECT * FROM users WHERE id = ?', 1)->first();
```

```
$db->exec('DELETE FROM users WHERE id = ?', 1)->rowCount();
```

事务 Transaction
--------------

[](#事务-transaction)

手动事务

```
$tx = $db->beginTransaction();
try {
    $data = [
        'name' => 'foo',
        'balance' => 0,
    ];
    $tx->insert('users', $data);
    $tx->commit();
} catch (\Throwable $ex) {
    $tx->rollback();
    throw $ex;
}
```

自动事务，执行异常自动回滚并抛出异常

```
$db->transaction(function (Mix\Database\Transaction $tx) {
    $data = [
        'name' => 'foo',
        'balance' => 0,
    ];
    $tx->insert('users', $data);
});
```

调试 Debug
--------

[](#调试-debug)

```
$db->debug(function (Mix\Database\ConnectionInterface $conn) {
        var_dump($conn->queryLog()); // array, fields: time, sql, bindings
    })
    ->table('users')
    ->where('id = ?', 1)
    ->get();
```

日志 Logger
---------

[](#日志-logger)

日志记录器，配置后可打印全部SQL信息

```
$db->setLogger($logger);
```

`$logger` 需实现 `Mix\Database\LoggerInterface`

```
interface LoggerInterface
{
    public function trace(float $time, string $sql, array $bindings, int $rowCount, ?\Throwable $exception): void;
}
```

License
-------

[](#license)

Apache License Version 2.0,

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance45

Moderate activity, may be stable

Popularity34

Limited adoption so far

Community23

Small or concentrated contributor base

Maturity70

Established project with proven stability

 Bus Factor1

Top contributor holds 96.8% 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 ~26 days

Recently: every ~135 days

Total

61

Last Release

1142d ago

Major Versions

v2.2.18 → v3.0.12021-07-06

PHP version history (2 changes)v2.0.1-Beta2PHP &gt;=7.0.0

v3.0.1PHP &gt;=7.2.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/16074765?v=4)[LIU JIAN](/maintainers/onanying)[@onanying](https://github.com/onanying)

---

Top Contributors

[![onanying](https://avatars.githubusercontent.com/u/16074765?v=4)](https://github.com/onanying "onanying (153 commits)")[![cexll](https://avatars.githubusercontent.com/u/26520956?v=4)](https://github.com/cexll "cexll (3 commits)")[![joanhey](https://avatars.githubusercontent.com/u/249085?v=4)](https://github.com/joanhey "joanhey (1 commits)")[![NHZEX](https://avatars.githubusercontent.com/u/14545600?v=4)](https://github.com/NHZEX "NHZEX (1 commits)")

---

Tags

databasemixpdopoolswooleworkermandatabasemysqlswooleworkermanmix

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[rah/danpu

Zero-dependency MySQL dump library for easily exporting and importing databases

64401.8k10](/packages/rah-danpu)

PHPackages © 2026

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