PHPackages                             chsxf/pdo-database-manager - 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. chsxf/pdo-database-manager

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

chsxf/pdo-database-manager
==========================

Database manager based on PDO with extension methods

2.0.5(1y ago)0261↓75%1MITPHPPHP ^8.0.7

Since Sep 5Pushed 1y agoCompare

[ Source](https://github.com/chsxf/pdo-database-manager)[ Packagist](https://packagist.org/packages/chsxf/pdo-database-manager)[ Docs](https://github.com/chsxf/pdo-database-manager)[ RSS](/packages/chsxf-pdo-database-manager/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (8)Used By (1)

About This Project
==================

[](#about-this-project)

The main purpose of this package is to extend the capabilities of [PDO](https://www.php.net/manual/en/book.pdo.php) by prodiving useful query methods to allow redaction of faster, safer and more reliable code.

Legacy Repository
-----------------

[](#legacy-repository)

I originally wrote this package while working on several tools and websites for my now defunct videogame studio called Cheese Burgames. As a fork, this repository is a continuation of the project.

Conventions
-----------

[](#conventions)

This repository uses [gitmoji](https://gitmoji.dev) for its commit messages.

Getting Started
===============

[](#getting-started)

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

[](#requirements)

- PHP 8.0.7+

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

[](#installation)

We strongly recommend using [Composer](https://getcomposer.org/) to install this package.

```
composer require chsxf/pdo-database-manager

```

Usage
-----

[](#usage)

The following uses a MySQL database but the same applies for [all database servers supported by PDO](https://www.php.net/manual/en/pdo.drivers.php). Adaptations may be needed though.

### Initialization

[](#initialization)

First, we have to load and initialize the database manager. PDO uses a [Data Source Name](https://www.php.net/manual/en/pdo.construct.php), or DSN, to convey connection information.

```
// Load the classes
require('vendor/autoload.php');
use \chsxf\PDO\DatabaseManager;

// Configuration - Adapt to fit your own configuration
$server_host = 'localhost';
$user = 'username';
$password = 'password';
$database_name = 'database_name';

// Initializing database manager
$dsn = "mysql:dbname={$database_name};host={$server_host}";
$dbm = new DatabaseManager($dsn, $user, $password);
```

### General Queries

[](#general-queries)

You can use the [`query`](https://www.php.net/manual/en/pdo.query.php) method to execute any query you like. In the context of this example, we create a temporary table to proceed with the rest of the helper functions.

```
if ($dbm->query('CREATE TEMPORARY TABLE `test_table` (
                `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                `label` varchar(255) COLLATE utf8_bin NOT NULL,
                `price` float unsigned NOT NULL,
                `stock` int(10) unsigned NOT NULL,
                PRIMARY KEY (`id`)
            )') === false) {
    die('Unable to create temporary table');
}
```

Both `query` and `exec` methods have been overridden to support error logging, among other things.

As most methods of the `DatabaseManager` class, `query` returns `false` in case of an error, so you can act accordingly.

### Executing Altering Statements with Placeholders

[](#executing-altering-statements-with-placeholders)

Use the [`exec`](https://www.php.net/manual/en/pdo.exec.php) method in order to retrieve the number of affected rows by an alterning statement like `UPDATE` or `DELETE`. In complement of error logging, this method has been overridden to allow execution of statements with placeholders and values in one call.

```
// Inserting sample data
$sql = 'INSERT INTO `test_table` (`label`, `price`, `stock`) VALUE (?, ?, ?)';
$values = [
        [ 'PHP for Dummies', 15.00, 100 ],
        [ 'The Lord of the Rings Trilogy', 46.74, 25 ],
        [ '1984', 13.42, 50 ]
];
foreach ($values as $rowValues) {
    if ($dbm->exec($sql, $rowValues) === false) {
        die('Unable to add sample data');
    }
}
```

### Retrieving a Single Specific Value

[](#retrieving-a-single-specific-value)

Use the `getValue` method to retrieve a single value from your database. As for the `exec` method, you can pass a statement with placeholders along with the replacement values in a single call, improving security and productivity.

```
$productLabel = '1984';
$productID = $dbm->getValue('SELECT `id` FROM `test_table` WHERE `label` = ?', $productLabel);
if ($productID === false) {
    die('Unable to retrieve product ID');
}
```

### Retrieval of a Specific Column

[](#retrieval-of-a-specific-column)

The `getColumn` method fetches the values of the first column returned by the provided statement.

```
$productLabels = $dbm->getColumn('SELECT `label` FROM `test_table` ORDER BY `label` ASC');
if ($productLabels === false) {
    die('Unable to retrieve product labels');
}
echo "Product labels:\n";
foreach ($productLabels as $label) {
    echo "\t- {$label}\n";
}
```

Outputs:

```
Product labels:
	- 1984
	- PHP for Dummies
	- The Lord of the Rings Trilogy

```

### Retrieval of a Specific Row

[](#retrieval-of-a-specific-row)

The `getRow` method fetches the first row returned by the provided statement.

Along with the `get` and `getIndexed` methods, you can specify how rows are fetched. At the moment, only `PDO::FETCH_ASSOC`, `PDO::FETCH_NUM`, `PDO::FETCH_OBJ` and `PDO::FETCH_BOTH` (PHP's default) are supported.

```
$productData = $dbm->getRow('SELECT * FROM `test_table` WHERE `id` = ?', \PDO::FETCH_ASSOC, $productID);
if ($productData === false) {
    die('Unable to retrieve product data');
}
echo "Specific row (as an associative array):\n";
foreach ($productData as $k => $v) {
    echo "\t- {$k}: {$v}\n";
}
```

Outputs:

```
Specific row (as an associative array):
	- id: 3
	- label: 1984
	- price: 13.42
	- stock: 50

```

### Retrieval of Several Rows

[](#retrieval-of-several-rows)

The `get` method fetches all rows returned by the previded statement.

```
$productData = $dbm->get('SELECT * FROM `test_table`', \PDO::FETCH_NUM);
if ($productData === false) {
    die('Unable to retrieve product data');
}
echo "Several rows (as numerically-indexed arrays):\n";
for ($i = 0; $i < count($productData); $i++) {
    $row = $productData[$i];
    echo "\tRow #{$i}:\n";
    foreach ($row as $k => $v) {
        echo "\t\t- {$k}: {$v}\n";
    }
}
```

Outputs:

```
Several rows (as numerically-indexed arrays):
	Row #0:
		- 0: 1
		- 1: PHP for Dummies
		- 2: 15
		- 3: 100
	Row #1:
		- 0: 2
		- 1: The Lord of the Rings Trilogy
		- 2: 46.74
		- 3: 25
	Row #2:
		- 0: 3
		- 1: 1984
		- 2: 13.42
		- 3: 50

```

### Retrieval of Rows Indexed by a Field Value

[](#retrieval-of-rows-indexed-by-a-field-value)

The `getIndexed` method fetches all rows returned by the provided statement, indexed by the value of a specific field.

```
$productData = $dbm->getIndexed('SELECT * FROM `test_table`', 'id', \PDO::FETCH_OBJ);
if ($productData === false) {
    die('Unable to retrieve product data');
}
echo "Indexed rows (as objects):\n";
foreach ($productData as $id => $row) {
    echo "\tProduct with ID #{$id}:\n";
    foreach ($row as $k => $v) {
        echo "\t\t- {$k}: {$v}\n";
    }
}
```

Outputs:

```
Indexed rows (as objects):
	Product with ID #1:
		- id: 1
		- label: PHP for Dummies
		- price: 15
		- stock: 100
	Product with ID #2:
		- id: 2
		- label: The Lord of the Rings Trilogy
		- price: 46.74
		- stock: 25
	Product with ID #3:
		- id: 3
		- label: 1984
		- price: 13.42
		- stock: 50

```

### Retrieval of Pairs of Values

[](#retrieval-of-pairs-of-values)

The `getPairs` method fetches pairs of values returned by the provided statement. The values of the first and second returned columns are used respectively as keys and values of the returned array.

```
$productPairs = $dbm->getPairs('SELECT `id`, `price` FROM `test_table` ORDER BY `price` DESC');
if ($productPairs === false) {
    die('Unable to retrieve price per ID');
}
echo "Pairs of values:\n";
foreach ($productPairs as $k => $v) {
    echo "\t- Price for product #{$k}: {$v}\n";
}
```

Outputs:

```
Pairs of values:
	- Price for product #2: 46.74
	- Price for product #1: 15
	- Price for product #3: 13.42

```

Error Logging
=============

[](#error-logging)

The `DatabaseManager` class provides an optional error logging system that can help a lot with debugging.

The errors are logged directly into the database in a specific table. **It is obviously NOT RECOMMENDED to use this error logging system in production environments.**

To enable error logging, pass `true` to the `$useDatabaseErrorLogging` parameter in the constructor.

Error Table Structure
---------------------

[](#error-table-structure)

In order to work, your database must include a table with the following structure:

```
CREATE TABLE `database_errors` (
  `query` text COLLATE utf8_bin NOT NULL,
  `error_code` int(11) NOT NULL,
  `error_message` text COLLATE utf8_bin NOT NULL,
  `file` text COLLATE utf8_bin NOT NULL,
  `line` int(11) NOT NULL,
  `function` text COLLATE utf8_bin NOT NULL,
  `class` text COLLATE utf8_bin NOT NULL
);
```

By default, the name of the table is `database_errors`, but you can change it by defining a constant named `chsxf\PDO\ERRORS_TABLE` before loading the `DatabaseManager` class.

```
define('chsxf\PDO\ERRORS_TABLE', 'my_custom_error_table_name');
use \chsxf\PDO\DatabaseManager;
```

License
=======

[](#license)

This project is released under the terms of the [MIT License](LICENSE).

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance43

Moderate activity, may be stable

Popularity13

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity60

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

Recently: every ~271 days

Total

7

Last Release

449d ago

Major Versions

0.9 → 2.02021-09-18

PHP version history (2 changes)0.9PHP ^8.0

2.0PHP ^8.0.7

### Community

Maintainers

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

---

Top Contributors

[![chsxf](https://avatars.githubusercontent.com/u/3322862?v=4)](https://github.com/chsxf "chsxf (21 commits)")

### Embed Badge

![Health badge](/badges/chsxf-pdo-database-manager/health.svg)

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

###  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)
