PHPackages                             p810/mysql-helper - 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. p810/mysql-helper

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

p810/mysql-helper
=================

A fluent query builder and lightweight data mapper for MySQL

3.2.0(6y ago)476[4 issues](https://github.com/p810/mysql-helper/issues)MITPHPPHP ^7.2CI failing

Since Jul 5Pushed 6y ago3 watchersCompare

[ Source](https://github.com/p810/mysql-helper)[ Packagist](https://packagist.org/packages/p810/mysql-helper)[ RSS](/packages/p810-mysql-helper/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (21)Used By (0)

mysql-helper
============

[](#mysql-helper)

> A fluent query builder and lightweight data mapper for MySQL

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

[](#installation)

This package is available through Packagist.

```
$ composer require p810/mysql-helper --no-dev

```

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

[](#getting-started)

### Using the query builder

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

Connect to MySQL with a new instance of `p810\MySQL\Connection`:

```
$connection = new p810\MySQL\Connection('username', 'password', 'database');
```

> **Note:** For more connection options, see [the documentation](docs/01_Getting_Started.md).

Then use the builder factory methods to fluently build your SQL queries with a `p810\MySQL\Builder\BuilderInterface` object:

```
$query = $connection->select()->from('users')->where('username', 'Bob');

$result = $query->execute();

if ($result) {
    foreach ($result as $row) {
        echo $row['username'] . '';
    }
}
```

The available factory methods are `select()`, `insert()`, `update()`, `delete()`, and `replace()`. To run a query and get its `PDOStatement` object (rather than process the results), you can run `p810\MySQL\Connection::query()`:

```
$statement = $connection->query('select last_insert_id() from users limit 1');
```

`query()` also supports binding input for prepared statements. Just pass an array after the query.

### Entities and data mappers

[](#entities-and-data-mappers)

You can make models of your domain logic by implementing `p810\MySQL\Mapper\EntityInterface`. These models can be mapped to MySQL via implementations of `p810\MySQL\Mapper\MapperInterface`. Most mappers should extend `p810\MySQL\Mapper\DefaultMapper`, as it handles most operations out of the box:

```
class User implements \p810\MySQL\Mapper\EntityInterface
{
    /**
     * @var string
     */
    public $username;

    /**
     * @var string
     */
    public $password;

    /**
     * {@inheritdoc}
     */
    public static function from(array $state): EntityInterface
    {
        return new self($state['username'], $state['password']);
    }

    /**
     * {@inheritdoc}
     */
    public function toArray(): array
    {
        return (array) $this;
    }

    /**
     * @param string $username
     * @param string $password
     */
    function __construct(string $username, string $password)
    {
        $this->username = $username;
        $this->password = $password;
    }
}
```

```
class UserMapper extends \p810\MySQL\Mapper\DefaultMapper
{
    /**
     * {@inheritdoc}
     */
    public $table = 'users';

    /**
     * {@inheritdoc}
     */
    public $key = 'user_id';

    /**
     * {@inheritdoc}
     */
    protected $entity = User::class;
}
```

> 💡 **Note:** The `$key` property is optional, but setting it allows you to use live entities, which are explained below. These entities have first class support for Active Record style methods, e.g. `Row::save()`.

When running a query via a mapper, you have the option to manipulate the `p810\MySQL\Query` that it generates by passing a callback to the method call:

```
$users = $mapper->read(function (\p810\MySQL\Query $query) use ($input) {
    return $query->where('username', $input['username'])
                 ->innerJoin('profiles')
                 ->using('user_id');
});
```

> 💡 **Note:** It's recommended that you specify your query's constraints in methods belonging to your mapper. Be careful not to run a CRUD method via the mapper without manipulating the query unless you have an absolute use case, otherwise you will end up with potentially large result sets or dangerous side effects. For example, `DefaultMapper::delete()` without any customization will delete *every* row in the table represented by your mapper.

If you want to run a generic query against the `p810\MySQL\Connection`, you can pass it through `MapperInterface::query()` which has the same signature as `Connection::raw()`.

### Live entities

[](#live-entities)

For users who are more accustomed to Active Record inspired models, your mapper may extend `p810\MySQL\Mapper\RowMapper` which provides all the functionality of `p810\MySQL\Mapper\DefaultMapper`, but returns instances of `p810\MySQL\Mapper\Row` which wrap your entity and mapper for a less verbose experience:

```
$user->password = 'some_new_password1@%';

// This is equivalent to calling DefaultMapper::updateById(1, $user)
$user->save();
```

For more information on what's possible with the query builder and data mapper, check out [the documentation](docs/03_Data_Mapper.md).

Development
-----------

[](#development)

### Unit testing

[](#unit-testing)

```
$ ./bin/migrate
$ ./vendor/bin/phpunit ./test/

```

A file named `.db.env` is loaded when PHPUnit is run, to get database connection options. An example of this file's contents can be found in `.db.env.example`. To change the location of this file, modify the environment variable in `phpunit.xml`. To point the migration script to an alternate file you can pass the `-f` or `--file` flag with the relative path to your file.

### Code quality

[](#code-quality)

```
$ ./vendor/bin/psalm --show-info=false

```

License
-------

[](#license)

This package is released under the [MIT License](https://github.com/p810/mysql-helper/blob/master/LICENSE).

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance0

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity67

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

Recently: every ~48 days

Total

19

Last Release

2384d ago

Major Versions

v1.3.1 → 2.0.02018-09-12

2.1.2 → 3.0.02019-04-29

PHP version history (2 changes)2.0.0PHP ^7.1

3.0.0PHP ^7.2

### Community

Maintainers

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

---

Top Contributors

[![p810](https://avatars.githubusercontent.com/u/3998736?v=4)](https://github.com/p810 "p810 (483 commits)")

---

Tags

data-mappermysqlormphpquery-builder

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/p810-mysql-helper/health.svg)

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

###  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)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

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

Reliese Components for Laravel Framework code generation.

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

PHPackages © 2026

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