PHPackages                             silverslice/easydb - 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. silverslice/easydb

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

silverslice/easydb
==================

Easy to use mysqli wrapper

v0.1.1(10y ago)1381MITPHPPHP &gt;=5.4

Since Aug 26Pushed 10y ago1 watchersCompare

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

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

EasyDb
======

[](#easydb)

[![Coverage Status](https://camo.githubusercontent.com/669da961dacc73000776a463e2f5d27bea1bfc6379ae9e369e30bb921a0dcf7a/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f73696c766572736c6963652f6561737964622f62616467652e7376673f6272616e63683d6d617374657226736572766963653d676974687562)](https://coveralls.io/github/silverslice/easydb?branch=master)

EasyDb is a simple wrapper over standart myslqi extension.

What does this library offer you?

- Use placehoders with different types to pass data into query safely.
- Select one cell or all rows with only one method.
- Insert and update rows by passing column-value arrays.
- Use transactions with only one method.
- Executes multiple queries to load your sql dumps.
- Peforms multiple inserts and `insert... on duplicate update` queries without ton of code.

Install
-------

[](#install)

Use composer to install library.

`composer require silverslice/easydb`

Connect to the database
-----------------------

[](#connect-to-the-database)

```
use Silverslice\EasyDb\Database;

// connect options
$options = [
    'host'     => 'localhost',
    'username' => 'root',
    'password' => '',
    'dbname'   => 'testdb',
    'charset'  => 'utf8'
];

// mysql options (not required)
$mysqlOptions = [MYSQLI_INIT_COMMAND => 'SET AUTOCOMMIT = 0'];

$db = new Database($options, $mysqlOptions);
```

Placeholders
------------

[](#placeholders)

EasyDb uses placeholders to place data in the query.

### Types of placeholders

[](#types-of-placeholders)

`?` - smart

In most cases you can use this placeholder. It automatically detects your value and correctly formats it.

- Integer value will be inserted as is.
- Null value will be inserted as NULL keyword.
- Database expressions will be inserted as is.
- In other cases value will be inserted as string.

`?i` - integer

Value will be cast to int with intval function.

`?s` - string

Value will be escaped with mysqli internal escape function and will be wrapped with single quote.

`?f` - float

Value will be cast to float with floatval function.

`?a` - array

This placeholder expects array, correctly escapes and quotes its values, and separates them by comma. It is useful in queries like `SELECT * FROM table WHERE id IN (1, 2, 3)`

```
$db->getAll('SELECT * FROM table WHERE id IN (?a)', [1, 2, 3]);

// generated sql: SELECT * FROM table WHERE id IN (1, 2, 3)
```

`?u` - set

This placeholder expects column-value array and generates code for SET clouse

```
$db->query('UPDATE products SET ?u', ['key' => 'foo', 'value' => 1]);

// generated sql: UPDATE products SET `key` = 'foo', `value` = 1
```

`?e` - escape

Value will be escaped with mysqli internal escape function.

`?p` - part

Value will be inserted as is. Use this placeholder to insert already prepared part of sql query.

### Make query dinamically

[](#make-query-dinamically)

If your query depends on some conditions you can use `prepare` method to replace all placeholders in string with passed parameters. This string may be inserted into query safely.

```
$pricePart = '';
if ($price) {
    $pricePart = $db->prepare(' AND price < ?', $price);
}

$db->getAll('SELECT * FROM products WHERE category_id = ? ?p', $categoryId, $pricePart);
```

Exceptions
----------

[](#exceptions)

EasyDb converts all database errors to `\Silverslice\EasyDb\Exception`. Use `getQuery` method to get the query which caused an error.

**Example:**

```
try {
    $this->db->query("SELECTT 1");
} catch (Exception $e) {
    // get error code
    $code = $e->getCode();

    // get query with error
    $query = $e->getQuery();

    // get error message: code, error and query
    $message = $e->getMessage();
}
```

Selecting rows
--------------

[](#selecting-rows)

### getOne

[](#getone)

Peforms query and fetchs first cell from the first result row

*Parameters:*

- *string* $query - The SQL query
- *mixed* $param1 - Parameter for the first placeholder
- *mixed* $param2 - Parameter for the second placeholder
- ...

```
getOne($query, $param1, $param2...)
```

*Returns:*

- *string|null*

### getAssoc

[](#getassoc)

Peforms query and fetchs first result row as an associative array

```
getAssoc($query, $param1, $param2...)
```

*Returns:*

- *array|null*

### getAll

[](#getall)

Peforms query and fetchs all result rows as an associative array

```
getAll($query, $param1, $param2...)
```

*Returns:*

- *array*

### getColumn

[](#getcolumn)

Peforms query and fetchs one column from the result set as an enumerate array

```
getColumn($query, $param1, $param2...)
```

*Returns:*

- *array*

### getPairs

[](#getpairs)

Peforms query and fetchs key-value pairs from the result set.

```
getPairs($query, $param1, $param2...)
```

*Returns:*

- *array*

### getAllKeyed

[](#getallkeyed)

Peforms query and fetchs key-values pairs from the result set.

```
getAllKeyed($query, $param1, $param2...)
```

*Returns:*

- *array|bool*

Modifying rows
--------------

[](#modifying-rows)

### insert

[](#insert)

Inserts row into table

```
insert($table, $params, $ignore = false)
```

*Parameters:*

- *string* $table - Table name
- *array* $params - Column-value pairs
- *bool* $ignore - Use or not IGNORE keyword

*Returns:*

- *mixed* - Inserted row id or true if table hasn't autoincrement field

### update

[](#update)

Updates table rows

```
update($table, $params, $where = array())
```

*Parameters:*

- *string* $table - Table name
- *array* $params - Column-value pairs
- *array* $where - UPDATE WHERE clause(s). Several conditions will be concatenated with AND keyword

*Returns:*

- *int* - The number of affected rows

### insertUpdate

[](#insertupdate)

Inserts or updates table row using INSERT... ON DUPLICATE KEY UPDATE clause

```
insertUpdate($table, $insert, $update = array())
```

*Parameters:*

- *string* $table - Table name
- *array* $insert - Column-value pairs to insert
- *array* $update - Column-value pairs to update if key already exists in table

*Returns:*

- *int* - The number of affected rows: 1 if row was inserted or 2 if row was updated

### multiInsert

[](#multiinsert)

Inserts multiple rows into table

```
multiInsert($table, $fields, $data, $ignore = false)
```

*Parameters:*

- *string* $table - Table name
- *array* $fields - Field names
- *array* $data - Two-dimensional array with data to insert
- *bool* $ignore - Use or not IGNORE keyword

*Returns:*

- *int* - The number of affected rows

### delete

[](#delete)

Deletes table rows

```
delete($table, $where = array())
```

*Parameters:*

- *string* $table - Table name
- *array* $where - UPDATE WHERE clause(s). Several conditions will be concatenated with AND keyword

*Returns:*

- *int* - The number of affected rows

Using transactions
------------------

[](#using-transactions)

### beginTransaction

[](#begintransaction)

Starts a transaction

```
beginTransaction()
```

### commit

[](#commit)

Commits the current transaction

```
commit()
```

### rollback

[](#rollback)

Rolls back current transaction

```
rollback()
```

### transaction

[](#transaction)

Runs code in transaction

```
transaction($process)
```

*Parameters:*

- *callable* $process - Callback to process

*Returns:*

- *bool* - True if transaction was successful commited, false otherwise

*Throws:*

- *\\Silverslice\\EasyDb\\Exception*

**Example:**

```
$this->db->transaction(function () {
    $this->db->query("INSERT INTO test (id, code, price) VALUES (3003, '1', 1)");
    $this->db->query("INSERT INTO test (id, code, price) VALUES (3004, '1', 1)");
});
```

Advanced
--------

[](#advanced)

### Expressions

[](#expressions)

Columns in SQL queries are sometimes expressions, not simply column names from a table. You can create an object of type Expression to insert expression into sql.

```
$this->db->insert('test', [
    'time' => new Expression('NOW()')
]);

// or use expression alias

$this->db->insert('test', [
    'time' => $this->db->expression('NOW()')
]);
```

### Multi queries

[](#multi-queries)

Use `multiQuery` method to execute several queries which are concatenated by a semicolon, for example to load sql dump from file.

#### multiQuery

[](#multiquery)

Executes one or multiple queries which are concatenated by a semicolon

```
multiQuery($queries)
```

*Parameters:*

- *string* $queries

*Returns:*

- *bool*

*Throws:*

- *\\Silverslice\\EasyDb\\Exception*

**Example:**

```
$this->db->multiQuery("
    DROP TABLE IF EXISTS `test`;
    CREATE TABLE `test` (
     `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
     `code` char(15) NOT NULL,
     `name` varchar(200) NOT NULL,
     `price` decimal(10,2) unsigned DEFAULT NULL,
     `order` int(11) unsigned DEFAULT 0,
     PRIMARY KEY (`id`),
     KEY `code` (`code`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    INSERT INTO test (id, code, name, price)
    VALUES
      (1, '001', 'Cup', 20.00),
      (2, '002', 'Plate', 30.50)
");
```

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity49

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

Every ~41 days

Total

2

Last Release

3867d ago

PHP version history (2 changes)v0.1.0PHP &gt;=5.3.3

v0.1.1PHP &gt;=5.4

### Community

Maintainers

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

---

Top Contributors

[![silverslice](https://avatars.githubusercontent.com/u/6722542?v=4)](https://github.com/silverslice "silverslice (35 commits)")

---

Tags

databasemysqldbmysqli

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/silverslice-easydb/health.svg)

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

###  Alternatives

[sergeytsalkov/meekrodb

The Simple PHP/MySQL Library

341387.0k10](/packages/sergeytsalkov-meekrodb)[stefangabos/zebra_database

An advanced, compact and lightweight MySQL database wrapper library, built around PHP's MySQLi extension.

11812.0k](/packages/stefangabos-zebra-database)[rah/danpu

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

64401.8k10](/packages/rah-danpu)[go/db

Database library

6624.1k](/packages/go-db)[krugozor/database

PHP class library for simple, convenient, fast and safe work with MySql database, using PHP mysqli extension and imitation of prepared queries.

392.5k](/packages/krugozor-database)[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)
