PHPackages                             ap-lib/mysql - 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. ap-lib/mysql

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

ap-lib/mysql
============

AP\\Mysql is a performance-oriented query builder built exclusively for MySQL. It leverages MySQL-specific features like INSERT IGNORE, REPLACE, ON DUPLICATE KEY UPDATE, partitions, and bulk operations for maximum efficiency

065PHP

Since Jul 3Pushed 8mo ago1 watchersCompare

[ Source](https://github.com/ap-lib/mysql)[ Packagist](https://packagist.org/packages/ap-lib/mysql)[ RSS](/packages/ap-lib-mysql/feed)WikiDiscussions main Synced today

READMEChangelogDependenciesVersions (1)Used By (0)

AP\\Mysql
=========

[](#apmysql)

AP\\Mysql is a ***performance-oriented*** query builder built exclusively for MySQL. It leverages MySQL-specific features like INSERT IGNORE, REPLACE, ON DUPLICATE KEY UPDATE, partitions, and bulk operations for maximum efficiency

Unlike generic query builders, **AP\\Mysql** does **not** attempt to be cross-database compatible. Instead, it is finely tuned to leverage **MySQL's native syntax and optimizations** for maximum efficiency.

[![MIT License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)

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

[](#installation)

```
composer require ap-lib/mysql
```

Features
--------

[](#features)

- Performance-oriented query builder for MySQL
- Supports INSERT, UPDATE, DELETE, SELECT, and REPLACE
- Bulk INSERT and REPLACE with query generators
- Secure escaping for values while keeping column names flexible
- Supports ON DUPLICATE KEY UPDATE
- Partitioning support

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

[](#requirements)

- PHP 8.3 or higher
- php-mysqli driver
- MySQL 8.4

Getting started
---------------

[](#getting-started)

### Connecting to the Database

[](#connecting-to-the-database)

```
use AP\Mysql\Connect\Connect;

$connect = new Connect(
    'localhost',
    'user',
    'password',
    'scheme'
);
```

### ⚠️ Important Security Notice

[](#️-important-security-notice)

For **performance reasons**, **all names (table, column, partition, etc.) are not automatically escaped**.
If you use **dynamic input**, manually sanitize names using:

```
use AP\Mysql\Helper;

$safeName = Helper::escapeName($userInput);
```

#### ✅ Values (data) are always properly escaped and safe

[](#-values-data-are-always-properly-escaped-and-safe)

### INSERT

[](#insert)

```
$insert = $connect->insert(
    'users',
    [
        'name' => "John Doe's market",
        'email' => 'john@example.com'
    ]
);

// execute
$insert->exec();

// or get query: INSERT `users`(`name`,`email`) VALUE ('John Doe\'s market','john@example.com')
echo $query->query();
```

### INSERT BULK

[](#insert-bulk)

```
$bulkInsert = $connect->insertBulk('users', [
    ['name' => 'John Doe', 'email' => 'john@example.com'],
    ['name' => 'Jane Doe', 'email' => 'jane@example.com']
]);

// execute
$bulkInsert->exec();

// or get queries
foreach ($bulkInsert->queries() as $query) {
    echo $query . PHP_EOL;
}
// INSERT `users`(`id`,`name`,`email`) VALUE (1,'John Doe','john@example.com'),(2,'Jane Doe','jane@example.com')
// by 1000 lines on one query by default
```

### INSERT ... SELECT

[](#insert--select)

```
$insert = $connect->insertSelect(
    "users",
    $connect->select('old_users', ['id', 'name', 'email']),
    ['id', 'username', 'email']
);

// execute
$bulkInsert->exec();

// or get query: INSERT `users`(`id`,`username`,`email`) SELECT `id`,`name`,`email` FROM `old_users`
echo $query;
```

### REPLACE

[](#replace)

```
$replace = $connect->replace(
    'users',
    [
        'id' => 1,
        'name' => 'John Doe',
        'email' => 'john@example.com'
    ]
);

// execute
$replace->exec();

// or get query: REPLACE `users`(`id`,`name`,`email`) VALUE (1,'John Doe','john@example.com')
echo $replace->query();
```

### REPLACE BULK

[](#replace-bulk)

```
$bulkReplace = $connect->replaceBulk('users', [
    ['id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com'],
    ['id' => 2, 'name' => 'Jane Doe', 'email' => 'jane@example.com']
]);

// execute
$bulkReplace->exec();

// or get queries
foreach ($bulkReplace->queries() as $query) {
    echo $query . PHP_EOL;
}
// REPLACE `users`(`id`,`name`,`email`) VALUE (1,'John Doe','john@example.com'),(2,'Jane Doe','jane@example.com')
// by 1000 lines on one query by default
```

### REPLACE ... SELECT

[](#replace--select)

```
$replace = $connect->replaceSelect(
    "users",
    $connect->select('old_users', ['id', 'name', 'email']),
    ['id', 'username', 'email']
);

// execute
$replace->exec();

// or get query: REPLACE `users`(`id`,`username`,`email`) SELECT `id`,`name`,`email` FROM `old_users`
echo $replace->query();
```

### DELETE

[](#delete)

```
$delete = $connect->delete("users", ['id' => 1]);

// execute
$delete->exec();

// or get query: DELETE FROM `users` WHERE `id`=1
echo $delete->query();
```

### SELECT

[](#select)

```
$select = $connect->select('users', ['id', 'name', 'email'])
    ->whereEq('status', 'active')
    ->order('name')
    ->setLimit(10);

// execute and get results
$results = $select->exec();

// or get query: SELECT `id`,`name`,`email` FROM `users` WHERE `status`='active' ORDER BY `name` LIMIT 10
echo $select->query();
```

### UPDATE

[](#update)

```
$update = $connect->update('users')
    ->assignment('status', 'paused')
    ->assignment('paused_at', new Raw('NOW()'))
    ->whereEq('id', 7);

// execute
$results = $update->exec();

// or get query: UPDATE `users` SET `status`='paused',`paused_at`=NOW() WHERE `id`=7
echo $update->query();
```

---

### WHERE Conditions

[](#where-conditions)

It allows chaining multiple conditions while ensuring values are properly escaped.
It can be used as a **sub-condition** inside **SELECT, DELETE, and UPDATE** queries.

```
$where = $connect->where()
    ->subWhere(
        $connect->where()
            ->whereEq('role', 'admin')
            ->whereGt('last_login', '2024-01-01')
    )
    ->orSubWhere(
        $connect->where()
            ->whereEq('role', 'moderator')
            ->whereLt('last_login', '2023-01-01')
    );

echo $where->query();
// OUTPUT: WHERE (`role`='admin' AND `last_login`>'2024-01-01')
//         OR (`role`='moderator' AND `last_login`select('users', ['id', 'name'])
    ->whereEq('status', 'active')
    ->whereGt('created_at', '2024-01-01');

// OUTPUT: SELECT `id`, `name` FROM `users` WHERE `status`='active' AND `created_at`>'2024-01-01'
echo $select->query();
```

#### Supported WHERE Operators

[](#supported-where-operators)

All **WHERE methods** have equivalent **HAVING methods** (e.g., `whereEq()` → `havingEq()`).

MethodSQL EquivalentExamplewhereEq($col, $val)column = valuewhereEq('id', 1) → WHERE `id`=1whereNotEq($col, $val)column &lt;&gt; valuewhereNotEq('id', 1) → WHERE `id`&lt;&gt;1whereGt($col, $val)column &gt; valuewhereGt('score', 50) → WHERE `score`&gt;50whereGte($col, $val)column &gt;= valuewhereGte('score', 50) → WHERE `score`&gt;=50whereLt($col, $val)column &lt; valuewhereLt('score', 50) → WHERE `score`&lt;50whereLte($col, $val)column &lt;= valuewhereLte('score', 50) → WHERE `score`&lt;=50whereLike($col, $val)column LIKE valuewhereLike('name', '%John%') → WHERE `name` LIKE '%John%'whereNotLike($col, $val)column NOT LIKE valuewhereNotLike('name', 'John%') → WHERE `name` NOT LIKE 'John%'whereIsNull($col)column IS NULLwhereIsNull('deleted\_at') → WHERE `deleted\_at` IS NULLwhereIsNotNull($col)column IS NOT NULLwhereIsNotNull('deleted\_at') → WHERE `deleted\_at` IS NOT NULLwhereBetween($col, $start, $end)column BETWEEN start AND endwhereBetween('age', 18, 25) → WHERE `age` BETWEEN 18 AND 25whereIn($col, $array)column IN (values)whereIn('id', \[1, 2, 3\]) → WHERE `id` IN (1,2,3)whereNotIn($col, $array)column NOT IN (values)whereNotIn('id', \[1, 2, 3\]) → WHERE `id` NOT IN (1,2,3)whereExists($subquery)EXISTS (subquery)whereExists($select) → WHERE EXISTS (SELECT id FROM users WHERE active=1)whereNotExists($subquery)NOT EXISTS (subquery)whereNotExists($select) → WHERE NOT EXISTS (SELECT id FROM users WHERE active=1)whereCond($rawCondition, ...$values)Custom conditionwhereCond("age &gt; %s AND score &lt; %s", 18, 50) → WHERE age &gt; 18 AND score &lt; 50### OR Conditions

[](#or-conditions)

For OR conditions, use the orWhere...() variants:

```
$select = $connect->select('users', ['id', 'name'])
    ->whereEq('status', 'active')
    ->orWhereEq('role', 'moderator');

// OUTPUT: SELECT `id`,`name` FROM `users` WHERE `status`='active' OR `role`='moderator'
echo $select->query();
```

### ORDER BY

[](#order-by)

Sorting records in **SELECT, UPDATE, and DELETE** queries:

```
$select = $connect->select('users', ['id', 'name'])
    ->whereEq('status', 'active')
    ->order('name')
    ->orderDesc('created_at');

// OUTPUT: SELECT `id`, `name` FROM `users` WHERE `status`='active' ORDER BY `name`, `created_at` DESC
echo $select->query();
```

#### Supported ORDER Methods

[](#supported-order-methods)

MethodSQL EquivalentExampleorder($col)ORDER BY column ASCorder('name') → ORDER BY `name`orderDesc($col)ORDER BY column DESCorderDesc('created\_at') → ORDER BY `created\_at` DESCorderExpr($expr)ORDER BY expressionorderExpr('LENGTH(name)') → ORDER BY LENGTH(name)orderExprDesc($expr)ORDER BY expression DESCorderExprDesc('RAND()') → ORDER BY RAND() DESC### GROUP BY

[](#group-by)

Used for aggregating records in **SELECT queries**:

```
$select = $connect->select(
    'users',
    [
        'role',
        'user_count' => new Raw('COUNT(*)')
    ]
)
    ->group('role');

// OUTPUT: SELECT `role`,COUNT(*) AS `user_count` FROM `users` GROUP BY `role`
echo $select->query();
```

#### Supported GROUP Methods

[](#supported-group-methods)

MethodSQL EquivalentExamplegroup($col)GROUP BY columngroup('category') → GROUP BY `category`groupExpr($expr)GROUP BY expressiongroupExpr('YEAR(created\_at)') → GROUP BY YEAR(created\_at)

###  Health Score

18

—

LowBetter than 10% of packages

Maintenance42

Moderate activity, may be stable

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/1215fe5ecc9ba0ab1c730d3c992125cf6ebf460562e66be71ebae127789d465a?d=identicon)[AntonPanfilov](/maintainers/AntonPanfilov)

---

Top Contributors

[![anton-panfilov](https://avatars.githubusercontent.com/u/1083546?v=4)](https://github.com/anton-panfilov "anton-panfilov (38 commits)")

### Embed Badge

![Health badge](/badges/ap-lib-mysql/health.svg)

```
[![Health](https://phpackages.com/badges/ap-lib-mysql/health.svg)](https://phpackages.com/packages/ap-lib-mysql)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k280.5M5.5k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k114.4M86](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k51.5M8.1k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k62.7M487](/packages/mongodb-mongodb)[spatie/laravel-translatable

A trait to make an Eloquent model hold translations

2.4k22.1M345](/packages/spatie-laravel-translatable)[kirschbaum-development/eloquent-power-joins

The Laravel magic applied to joins.

1.5k23.2M24](/packages/kirschbaum-development-eloquent-power-joins)

PHPackages © 2026

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