PHPackages                             rain1/pdo-powered - 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. rain1/pdo-powered

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

rain1/pdo-powered
=================

PDO wrapper for easy db interactions

1.0.0(2y ago)425MITPHPPHP &gt;= 8.1

Since Sep 27Pushed 2y ago2 watchersCompare

[ Source](https://github.com/LucaRainone/pdo-powered)[ Packagist](https://packagist.org/packages/rain1/pdo-powered)[ RSS](/packages/rain1-pdo-powered/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (1)Versions (6)Used By (0)

[![Build Status](https://camo.githubusercontent.com/e26e8ad7b9ea8249d5553ff088d7ea25dd6ff5855300d2ec50a198cf2b45deae/68747470733a2f2f7472617669732d63692e6f72672f4c7563615261696e6f6e652f70646f2d706f77657265642e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/LucaRainone/pdo-powered)[![Coverage Status](https://camo.githubusercontent.com/6a30dbe133260dfac3a40193d6aa05e619490f3a286b41cf47c4d64671fc0c70/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f4c7563615261696e6f6e652f70646f2d706f77657265642f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/LucaRainone/pdo-powered?branch=master)

PDOPowered is a wrapper for PDO providing following features:

- **lazy connection** The PDO instance is created only when needed. Configured credentials are deleted after the connection.
    - with `$db->onConnect($closure)` it's possible to do something after the connection.
- **reconnect on failure** try to reconnect if the connection fails (for `PDOPowered::$MAX_TRY_CONNECTION` tries).
    - with `$db->onConnectionFailure($closure)` it's possible to do something after every connection fail (for example a sleep and/or error reporting)
- **fast query params** prepare and execute are called in `query` method. `$db->query("SELECT ?,?,?", [1,2,3])`
- Query method returns a wrapper for `PDOStatement` with powered methods:
    - **fetchObjects** call `fetchObject` for each row and store the result in array
    - **getPDOStatement** for fetch the native PDOStatement.
- **fast queries** there are helpers for fast query:
    - **insert** for fast insert `$db->insert("tableName",$arrayValues)` returns the last insert id.
    - **update** for fast update `$db->update("tableName", $valuesToUpdate, $arrayCondition)` returns the count of affected rows.
    - **insertOnDuplicateKeyUpdate** for insert on duplicate key update `$db->insertOnDuplicateKeyUpdate($tableName, $arrayValues)` returns the last insert id.
    - **delete** for fast delete `$db->delete("tableName", $arrayWhereCondition)` returns the count of affected rows
- **easy debug** with `$db->onDebug($closure)` it's possible to access to debug output and do your stuff (log in file, send to stdoutput and so on)
- **access to native PDO instance** extending `PDOPowered` you have access to `getPDO()` method for any needs.

Basic Usage
-----------

[](#basic-usage)

### Installation

[](#installation)

```
composer require rain1/pdo-powered

```

or checkout

or download here ()

### Get Started

[](#get-started)

An implementation of rain1\\PDOPowered\\Config\\ConfigInterface must be passed to the constructor. We provide following implementations:

```
use \rain1\PDOPowered\Config\Config;
$config = new Config("mysql", "user", "password", "localhost", 3306, "dbname", "utf8", [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'']);
```

or equivalent

```
use \rain1\PDOPowered\Config\DSN;
$config = new DSN(
    "mysql:host=localhost;port=3306;dbname=dbname;charset=utf8", "user", "password"
);
$config->setOptions([\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"]);
```

So, we build the instance in this way:

```
$db = new PDOPowered($config);
```

It's possible to use PDOPowered with a pre-existent PDO instance

```
$db = PDOPowered::buildFromPDOInstance($pdoInstance);
```

The library provides shortcuts for insert / update / delete and update on duplicate key:

```
// fast insert. Return the inserted id
$id = $db->insert("tabletest", ['id'=>1, 'col1'=>'col1_1']);

// fast update
$db->update("tabletest", ['col1'=>'updated'], ['id'=>$id]);

// build a "INSERT ON DUPLICATE KEY UPDATE" query
$db->insertOnDuplicateKeyUpdate("tabletest", ['id'=> $id, 'col1'=>'updated']);
$db->insertOnDuplicateKeyUpdate("tabletest", ['id'=> $id+1, 'col1'=>'updated']);

// performs a delete
$db->delete("tabletest", ['id'=>$id]);

// simple query
$row = $db->query("SELECT * FROM tabletest WHERE id = ?", [$id])->fetch();

// or equivalent
$row = $db->query("SELECT * FROM tabletest WHERE id = :id", ['id'=>$id])->fetch();
```

The method `query` returns a wrapper of \\PDOStatement. Availabile methods:

- `fetch`
- `fetchAll`
- `fetchObject`
- `fetchColumn`
- `rowCount`
- `closeCursor`
- `getPDOStatement` returns the native PDOStatmenet (for any evenience)
- `fetchObjects` returns an array containing all of the result of `fetchObject` call

Advanced usage:
---------------

[](#advanced-usage)

Following events are triggered:

- connectionFailure
- connect
- debug

```
// triggered after a connection fails: before the next attempt
$db->onConnectionFailure(function($connectionTry, \Exception $exception) {
    sleep($connectionTry);
    error_log("Unable to connect on mysql: " . $exception->getMessage());
});

// triggered after a connection success
$db->onConnect(function() {
    echo "Db connected\n";
});

// triggered on debug string
$idDebugListener = $db->onDebug(function($debugType, \PDOStatement $PDOStatement = null, ...$args) {
    echo "$debugType\n";
    if($PDOStatement)
        $PDOStatement->debugDumpParams();
    echo "\n".json_encode($args);
});

// for each event we can remove the listener
$db->removeDebugListener($idDebugListener);
```

We provide an helper for easy debug

```
$db->onDebug(DebugParser::onParse(function ($info) {
    print_r($info); // info for timing, query, params and finalized query
}));
```

Other options:

```
// set maximum number of connection attempts.
\rain1\PDOPowered\Config\PDOPowered::$MAX_TRY_CONNECTION = 5;

// set pdo attribute after connection.
$db->setPDOAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
```

Param hints
-----------

[](#param-hints)

PDOPowered automatically considers value param strings as \\PDO::PARAM\_STR, and value integer as \\PDO::PARAM\_INT. For any evenience, you can do it explicitly:

```
$users = $db->query(
    "SELECT * FROM user WHERE email = :email AND id = :id",
    [
        "email" => new \rain1\PDOPowered\Param\ParamString("me@me.it"),
        "id"=> new \rain1\PDOPowered\Param\ParamInt("123"),
    ]
)->fetchAll();
```

And generally you can use every PDO Param supported:

```
[
    "param" => new \rain1\PDOPowered\Param\ParamNative("value", \PDO::PARAM_STR)
]
```

or build yourself a new Param type, implementing `\rain1\PDOPowered\Param\ParamInterface`.

For example as bonus we have:

```
[
    "param" => new \rain1\PDOPowered\Param\ParamJSON(["key"=>"value"])
]
```

this is equivalent to:

```
[
    "param" => json_encode(["key"=>"value"])
]
```

Real use case (try me at home)
------------------------------

[](#real-use-case-try-me-at-home)

You need to create a database "test".

```
use rain1\PDOPowered\Config\Config;
use rain1\PDOPowered\Debug\DebugParser;
use rain1\PDOPowered\Param\ParamJSON;
use rain1\PDOPowered\Param\ParamString;
use rain1\PDOPowered\PDOPowered;

require "vendor/autoload.php";

function output(...$texts) {
    $endline =  php_sapi_name() === "cli" ? "\n" : "";
    foreach($texts as $text)
        echo str_replace("\n", $endline, $text) .$endline;
}

$config = new Config(
    "mysql",
    "root",
    "vagrant",
    "localhost",
    3306,
    "test",
    "utf8",
    [
        \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
    ]
);

$db = new PDOPowered($config);

output("adding listeners...");

$db->onConnectionFailure(function ($try, \Exception $e) {
    error_log("connection failed: " . $e->getMessage());
    output("connection failed");
});

$db->onConnect(function() {
    output("Connected", "");
});

// only for debug
$debug = 1;
$countQuery = 0;
$debug && $db->onDebug(
    DebugParser::onParse(
        function ($info) use (&$countQuery) {

            $str = "---- DEBUG ROW " . (++$countQuery) .  " ----\n";

            if (isset($info['query']))
                $str .= $info['query']['demo'] . "\nexecution time: " . $info['query']['executionTime'];
            else
                $str .= $info['type'] . " " . json_encode($info['args']);

            output($str, "");
        }
    )
);

output("set attributes");

$db->setPDOAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);

output("first query");

$db->query("DROP TABLE IF EXISTS user");

$db->query("create table user
(
	id int auto_increment
		primary key,
	email varchar(32) null,
	settings text null
)
; ");

$db->beginTransaction();
$id = $db->insert("user", ['email' => 'me@me.com']);

$db->update("user", ["email" => "me2@me.com"], ['id' => (int)$id]);

$db->delete("user", ['id' => 1]);

$db->insert("user", [
    'id' => 1,
    'email' => new ParamString("me@me.com")
]);

$db->insertOnDuplicateKeyUpdate("user", [
    'id' => 1,
    'email' => new ParamString("me3@me.com"),
    'settings' => new ParamJSON(['privacy' => 1, 'newsletter' => 'no'])
]);

$rows = $db->query("SELECT * FROM user WHERE id = :id", ['id' => 1])->fetchAll();
$db->commitTransaction();

$db->query("SELECT SLEEP (1)");

print_r($rows);
```

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity74

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

Total

4

Last Release

751d ago

Major Versions

0.11.0 → 1.0.02024-04-23

PHP version history (2 changes)0.9.0PHP &gt;= 7.0

1.0.0PHP &gt;= 8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/45843806?v=4)[ChumKiu](/maintainers/chumkiu)[@ChumKiu](https://github.com/ChumKiu)

---

Top Contributors

[![LucaRainone](https://avatars.githubusercontent.com/u/1136293?v=4)](https://github.com/LucaRainone "LucaRainone (31 commits)")

---

Tags

mysqlpdophpquerysqlwrapperdatabasemysqlsqlpdodb

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/rain1-pdo-powered/health.svg)

```
[![Health](https://phpackages.com/badges/rain1-pdo-powered/health.svg)](https://phpackages.com/packages/rain1-pdo-powered)
```

###  Alternatives

[aura/sqlquery

Object-oriented query builders for MySQL, Postgres, SQLite, and SQLServer; can be used with any database connection library.

4572.9M34](/packages/aura-sqlquery)[atlas/query

Object-oriented query builders and performers for MySQL, Postgres, SQLite, and SQLServer.

41249.0k7](/packages/atlas-query)[aura/sqlschema

Provides facilities to read table names and table columns from a database using PDO.

41234.1k4](/packages/aura-sqlschema)[rah/danpu

Zero-dependency MySQL dump library for easily exporting and importing databases

64401.8k10](/packages/rah-danpu)[davmixcool/php-dbcloud

Easily backup PostgreSql or MySql database to the cloud

111.5k](/packages/davmixcool-php-dbcloud)

PHPackages © 2026

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