PHPackages                             hstanleycrow/easyphpdbcore - 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. hstanleycrow/easyphpdbcore

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

hstanleycrow/easyphpdbcore
==========================

Lightweight PDO-based database layer with a simple CRUD model for PHP.

v1.0.0(1mo ago)021↓75%1MITPHPPHP ^8.2

Since Jul 12Pushed 1mo agoCompare

[ Source](https://github.com/hstanleycrow/EasyPHPDBCore)[ Packagist](https://packagist.org/packages/hstanleycrow/easyphpdbcore)[ Docs](https://github.com/hstanleycrow/EasyPHPDBCore)[ RSS](/packages/hstanleycrow-easyphpdbcore/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (4)Versions (2)Used By (1)

English | [Español](README.es.md)

EasyPHPDBCore
=============

[](#easyphpdbcore)

Lightweight PDO-based database layer for PHP, with a simple CRUD `Model` and prepared statements everywhere.

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

[](#requirements)

- PHP 8.2 or higher
- Composer
- PDO with the `pdo_mysql` driver (for the MySQL/MariaDB connection)

Runtime dependency: [`psr/log`](https://packagist.org/packages/psr/log). A PSR-3 logger is optional; without one, errors are simply thrown as exceptions.

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

[](#installation)

```
composer require hstanleycrow/easyphpdbcore
```

Quick example
-------------

[](#quick-example)

```
use hstanleycrow\EasyPHPDBCore\Model;
use hstanleycrow\EasyPHPDBCore\Connection\MySQLEnvConfig;
use hstanleycrow\EasyPHPDBCore\Connection\MySQLPDOConnection;
use hstanleycrow\EasyPHPDBCore\Connection\MySQLEnvCharsetConfig;

require 'vendor/autoload.php';

// $_ENV must hold DATABASE_HOST, DATABASE_NAME, DATABASE_USERNAME,
// DATABASE_PASSWORD, DATABASE_PORT and DATABASE_CHARSET.
$connection = new MySQLPDOConnection(
    new MySQLEnvConfig($_ENV),
    new MySQLEnvCharsetConfig($_ENV)
);

class User extends Model
{
    protected ?string $table = 'users';
}

$user = new User($connection);

$id = $user->create([
    'name' => 'Harold',
    'username' => 'hstanleycrow',
    'active' => 'S',
])->lastInsertId();

$record = $user->getById($id);

$user->update(['name' => 'Harold Crow'], ['id' => $id]);

$user->delete(['id' => $id]);
```

Every write uses prepared statements with bound values, so array keys become column names and array values become bound parameters. Never interpolate user input into `query()` strings; pass it through the bindings instead.

Custom read queries
-------------------

[](#custom-read-queries)

`getRecords()` accepts positional or named bindings:

```
class User extends Model
{
    protected ?string $table = 'users';

    public function getActive(): array
    {
        return $this->query('SELECT id, name FROM users WHERE active = ? ORDER BY id')
            ->getRecords(['S']);
    }
}
```

Optional logging
----------------

[](#optional-logging)

Any [PSR-3](https://www.php-fig.org/psr/psr-3/) logger can be injected as the last constructor argument of the connection and the model (or the record classes). When omitted, a `NullLogger` is used and failures are only thrown.

```
$logger = new Monolog\Logger('app');
$logger->pushHandler(new Monolog\Handler\StreamHandler('php://stderr'));

$connection = new MySQLPDOConnection(new MySQLEnvConfig($_ENV), new MySQLEnvCharsetConfig($_ENV), $logger);
$user = new User($connection, $logger);
```

Error handling
--------------

[](#error-handling)

All failures throw typed exceptions instead of printing anything:

- `hstanleycrow\EasyPHPDBCore\Exception\ConnectionException` — connection/config errors.
- `hstanleycrow\EasyPHPDBCore\Exception\QueryException` — query execution errors.

Both extend `hstanleycrow\EasyPHPDBCore\Exception\DatabaseException`, so you can catch either one specifically or the base class for all database errors.

Public API
----------

[](#public-api)

### `Model`

[](#model)

MethodDescription`__construct(IConnection $connection, ?LoggerInterface $logger = null)`Build a model. Subclasses set `protected ?string $table`.`create(array $fieldsList): self`Insert a row. Keys are columns, values are bound.`lastInsertId(): ?int`Id generated by the last `create()`.`query(string $query): self`Set a raw SELECT to run with `getRecords()`.`getRecords(array $bindings = []): array`Run the current query and return rows as associative arrays.`getById(int|string $id): ?array``SELECT *` by primary key; `null` if not found.`update(array $updateFields, array $whereConditions): self`Update rows matching all where conditions.`delete(array $whereConditions): self`Delete rows matching all where conditions.`beginTransaction() / commit() / rollback(): void`Transaction control on the underlying PDO.### Connection

[](#connection)

ClassDescription`Connection\MySQLPDOConnection`Opens a real PDO MySQL/MariaDB connection.`Connection\MockConnection`No-op connection for tests.`Connection\MySQLEnvConfig` / `MySQLEnvCharsetConfig`Read credentials/charset from an env array.`Connection\IConnection` / `IConfig` / `ICharsetConfig`Interfaces to plug in your own implementations.### Record classes (used internally by `Model`, usable standalone)

[](#record-classes-used-internally-by-model-usable-standalone)

`CreateRecords`, `ReadRecords`, `UpdateRecords`, `DeleteRecords` each expose an `execute(...)` method and share the same `(IConnection, string $table, ?LoggerInterface)`constructor shape (`ReadRecords` takes the query instead of a table).

Testing
-------

[](#testing)

```
composer install
composer test
```

The test suite runs against an in-memory SQLite database, so no MySQL server is required.

License
-------

[](#license)

MIT — see [LICENSE](LICENSE).

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance90

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity46

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

Unknown

Total

1

Last Release

50d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/713da77764977a76a357f6b34361a7ab51bd55ea847b84112e3a38f5496af173?d=identicon)[hstanleycrow](/maintainers/hstanleycrow)

---

Top Contributors

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

---

Tags

phpdatabasemysqlmariadbpdomodelcrudquery builder

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/hstanleycrow-easyphpdbcore/health.svg)

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

###  Alternatives

[doctrine/dbal

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

9.9k624.3M7.6k](/packages/doctrine-dbal)[cycle/database

DBAL, schema introspection, migration and pagination

71853.9k81](/packages/cycle-database)[clouddueling/mysqldump-php

PHP version of mysqldump cli that comes with MySQL

1.3k23.3k](/packages/clouddueling-mysqldump-php)[tommyknocker/pdo-database-class

Framework-agnostic PHP database library with unified API for MySQL, MariaDB, PostgreSQL, SQLite, MSSQL, and Oracle. Query Builder, caching, sharding, window functions, CTEs, JSON, migrations, ActiveRecord, CLI tools, AI-powered analysis. Zero external dependencies.

826.3k](/packages/tommyknocker-pdo-database-class)

PHPackages © 2026

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