PHPackages                             khaderhan/secure-db - 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. khaderhan/secure-db

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

khaderhan/secure-db
===================

Secure, beginner-friendly PDO-first DBAL for native PHP (prepared statements, IN expansion, streaming, transactions).

v1.0.0(4mo ago)125↓78.6%MITPHPPHP ^8.2CI passing

Since Feb 25Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/khaderhan/secure-db)[ Packagist](https://packagist.org/packages/khaderhan/secure-db)[ RSS](/packages/khaderhan-secure-db/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

Secure DB (khaderhan/secure-db)
===============================

[](#secure-db-khaderhansecure-db)

[![CI](https://github.com/khaderhan/secure-db/actions/workflows/ci.yml/badge.svg)](https://github.com/khaderhan/secure-db/actions/workflows/ci.yml)
[![PHP Version](https://camo.githubusercontent.com/c2588b5670f2c910b8cc849ace22a22efda8956b7c2f797d11d2096bbfc7b1f5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d3737374242342e737667)](https://www.php.net/)
[![License: MIT](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

A secure-by-default, PDO-first database abstraction layer (DBAL) for **native PHP applications (PHP 8.2+)**.

> ⚠️ This package is designed for **framework-less / native PHP projects**.
> It does not integrate with Laravel, Symfony, or other framework ORMs.
> It is intentionally lightweight, explicit, and framework-independent.

---

Philosophy
==========

[](#philosophy)

Secure DB is intentionally minimal and explicit.

It is **not an ORM**.

It does not:

- Auto-map entities
- Generate SQL
- Hide SQL from the developer
- Replace full-featured framework database layers

Instead, it:

- Encourages explicit SQL
- Enforces safe parameter handling
- Provides ergonomic helpers
- Preserves full PDO power
- Keeps abstraction thin and predictable

Suitable for:

- Native PHP applications
- Microservices
- SaaS platforms
- Internal tools
- Performance-critical systems

---

Installation
============

[](#installation)

```
composer require khaderhan/secure-db
```

Requirements:

- PHP 8.2+
- ext-pdo
- pdo\_mysql (MySQL currently supported)

---

Quick Start
===========

[](#quick-start)

```
use Khaderhan\SecureDb\DB;

$db = DB::connect([
    'driver' => 'mysql',
    'host' => '127.0.0.1',
    'port' => 3306,
    'database' => 'example',
    'user' => 'root',
    'pass' => '',
    'charset' => 'utf8mb4',
    'dev' => true,
    'strict' => true,
]);

$users = $db->all(
    'SELECT * FROM users WHERE status = :status',
    ['status' => 'active']
);
```

---

Connection Configuration
========================

[](#connection-configuration)

Using DSN
---------

[](#using-dsn)

```
$db = DB::connect([
    'dsn' => 'mysql:host=127.0.0.1;port=3306;dbname=example;charset=utf8mb4',
    'user' => 'root',
    'pass' => '',
]);
```

Structured Config
-----------------

[](#structured-config)

```
$db = DB::connect([
    'driver' => 'mysql',
    'host' => '127.0.0.1',
    'port' => 3306,
    'database' => 'example',
    'user' => 'root',
    'pass' => '',
    'charset' => 'utf8mb4',
    'dev' => false,
    'strict' => true,
    'log_queries' => false,
    'query_log_size' => 50,
    'allow_empty_in_list' => false,
]);
```

---

Core API
========

[](#core-api)

query(string $sql, array $params = \[\]): Result
------------------------------------------------

[](#querystring-sql-array-params---result)

Used for SELECT queries.

exec(string $sql, array $params = \[\]): Result
-----------------------------------------------

[](#execstring-sql-array-params---result)

Used for INSERT / UPDATE / DELETE.

Both return a `Result` object.

---

Result Object API
=================

[](#result-object-api)

- ok(): bool\\
- affected(): int\\
- insertId(): int|string|null\\
- one(): ?array\\
- all(): array\\
- scalar(int|string $key = 0): mixed\\
- column(int|string $key = 0): array\\
- pairs(int|string $key = 0, int|string $value = 1): array\\
- iterate(): Generator\\
- mustOk(): self\\
- mustAffect(): self\\
- close(): void

Example:

```
$user = $db->query(
    'SELECT * FROM users WHERE id = :id',
    ['id' => 1]
)->one();
```

---

Helper Shortcuts
================

[](#helper-shortcuts)

- one()
- all()
- value()
- exists()
- column()
- pairs()

Example:

```
$count = $db->value('SELECT COUNT(*) FROM users');
$exists = $db->exists(
    'SELECT 1 FROM users WHERE email = :email',
    ['email' => 'test@example.com']
);
```

---

IN(:list) Expansion
===================

[](#inlist-expansion)

Safely supports array expansion inside IN clauses.

```
$rows = $db->all(
    'SELECT * FROM users WHERE status IN (:st)',
    ['st' => ['active', 'trial']]
);
```

Rules:

- Arrays allowed only inside `IN (:name)` contexts
- Empty array throws `InvalidArgumentException` by default
- If `allow_empty_in_list=true` → becomes `IN (NULL)`

---

Strict Parameter Normalization
==============================

[](#strict-parameter-normalization)

Automatically converts:

- bool → int (1/0)
- DateTimeInterface → formatted string
- Allows: string, int, float, null
- Rejects objects/resources (strict mode)

---

Transactions
============

[](#transactions)

Manual
------

[](#manual)

```
$db->begin();
$db->exec(...);
$db->commit();
```

Automatic
---------

[](#automatic)

```
$db->transaction(function(DB $db) {
    $db->exec(...);
    $db->exec(...);
});
```

Nested transactions use SAVEPOINT internally.

---

Streaming Large Result Sets
===========================

[](#streaming-large-result-sets)

```
foreach ($db->query('SELECT * FROM big_table')->iterate() as $row) {
    process($row);
}
```

Prevents loading large datasets into memory.

---

Repository Pattern Example
==========================

[](#repository-pattern-example)

```
final class UserRepository
{
    public function __construct(private DB $db) {}

    public function findById(int $id): ?array
    {
        return $this->db->one(
            'SELECT * FROM users WHERE id = :id',
            ['id' => $id]
        );
    }

    public function create(string $email): int
    {
        return $this->db->exec(
            'INSERT INTO users (email) VALUES (:email)',
            ['email' => $email]
        )->insertId();
    }
}
```

---

Performance Notes
=================

[](#performance-notes)

- Uses native prepared statements (ATTR\_EMULATE\_PREPARES=false)
- Streaming via generators
- Optional bounded query logging
- Nested transactions via SAVEPOINT
- utf8mb4 enforced by default

For high-throughput systems:

- Disable dev mode
- Disable query logging
- Use streaming for large results
- Ensure proper DB indexing

---

Security Notes
==============

[](#security-notes)

- Prepared statements protect values, not identifiers
- Always whitelist identifiers before using `DB::ident()`
- Escape output with `htmlspecialchars()`
- Use least-privilege database users
- Production mode hides SQL details

---

Error Handling
==============

[](#error-handling)

Throws:

- `InvalidArgumentException` (parameter validation issues)
- `DbException` (database-level errors)

Production mode does not leak SQL details.

---

Testing &amp; Static Analysis
=============================

[](#testing--static-analysis)

Run tests:

```
vendor/bin/phpunit
```

Run static analysis:

```
vendor/bin/phpstan analyse
```

---

Attribution &amp; Project History
=================================

[](#attribution--project-history)

This project was originally inspired by a MySQL database class published by:

**David Adams**
[https://codeshack.io/super-fast-php-mysql-database-class/\\](https://codeshack.io/super-fast-php-mysql-database-class/%5C)Published: 2020-03-05
License: MIT

David's original class provided a fast and simple mysqli-based implementation and served as a great starting point.

This repository represents a complete architectural redesign and modernization, including:

- Migration from mysqli to PDO
- Strict parameter handling
- Safe IN expansion
- Nested transactions
- Streaming support
- PSR-4 packaging
- PHPUnit + PHPStan verification
- CI pipeline integration

While inspired by the original work, this implementation is now a significantly expanded and refactored production-grade library.

Special thanks to David Adams for the original foundation.

---

License
=======

[](#license)

MIT License

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance76

Regular maintenance activity

Popularity11

Limited adoption so far

Community7

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

128d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/76283b589940247f3552860d6056c2d7337997f8da0b7c9c0512128e6b020fbc?d=identicon)[khaderhan](/maintainers/khaderhan)

---

Top Contributors

[![khaderhan](https://avatars.githubusercontent.com/u/47462919?v=4)](https://github.com/khaderhan "khaderhan (9 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/khaderhan-secure-db/health.svg)

```
[![Health](https://phpackages.com/badges/khaderhan-secure-db/health.svg)](https://phpackages.com/packages/khaderhan-secure-db)
```

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k117.2M118](/packages/jdorn-sql-formatter)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8351.6M87](/packages/propel-propel1)[jfelder/oracledb

Oracle DB driver for Laravel

11518.4k](/packages/jfelder-oracledb)

PHPackages © 2026

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