A small, speedy database abstraction layer for PHP

v5.0.0 2015-09-14 02:23 UTC


Packagist Version Total Downloads License Build Status

PeachySQL is a speedy database abstraction layer which makes it easy to execute prepared statements and work with large amounts of data. It supports both MySQL and SQL Server, and runs on PHP 5.5+ as well as HHVM.

Install via Composer

composer require theodorejb/peachy-sql


Start by instantiating the Mysql or SqlServer class with a database connection, which should be an existing mysqli object or SQLSRV connection resource:

$peachySql = new PeachySQL\Mysql($mysqlConn);


$peachySql = new PeachySQL\SqlServer($sqlSrvConn);

After instantiation, arbitrary statements can be prepared by passing a SQL string and array of bound parameters to the prepare method:

$sql = "UPDATE Users SET fname = ? WHERE user_id = ?";
$stmt = $peachySql->prepare($sql, [&$fname, &$id]);

$nameUpdates = [
    3 => 'Theodore',
    7 => 'Luke',

foreach ($nameUpdates as $id => $fname) {


Most of the time prepared statements only need to be executed a single time. To make this easier, PeachySQL provides a query method which automatically prepares, executes, and closes a statement after results are retrieved:

$sql = 'SELECT * FROM Users WHERE fname LIKE ? AND lname LIKE ?';
$result = $peachySql->query($sql, ['theo%', 'b%']);
echo json_encode($result->getAll());

Both prepare and query return a Statement object with the following methods:

Method Behavior
execute Executes the prepared statement (automatically called when using query).
getIterator Returns a Generator object which can be used to iterate over large result sets without caching them in memory.
getAll Returns all selected rows as an array of associative arrays.
getFirst Returns the first selected row as an associative array (or null if no rows were selected).
getAffected Returns the number of rows affected by the query.
close Closes the prepared statement and frees its resources (automatically called when using query).

If using MySQL, the Mysql\Statement object additionally includes a getInsertId method.

Internally, getAll and getFirst are implemented using getIterator. As such they can only be called once for a given statement.


PeachySQL comes with five shorthand methods for selecting, inserting, updating, and deleting records. To use these methods, a table name must be specified by passing an options object as the second argument to the PeachySQL constructor.

$options = new PeachySQL\Mysql\Options();


$options = new PeachySQL\SqlServer\Options();

Note: each of the options setter methods has a corresponding getter method (e.g. getTable) to retrieve the current setting value.

If using SQL Server, there is an additional option to set the table's identity column. This is necessary so that PeachySQL can generate an output clause to retrieve insert IDs.

$userTable = new PeachySQL\SqlServer($sqlSrvConn, $options);

Shorthand methods

Note: to prevent SQL injection, the queries PeachySQL generates for these methods always use bound parameters for values, and column names are automatically escaped.


The select method takes three arguments, all of which are optional:

  1. An array of columns to select.
  2. A WHERE array to filter results.
  3. An array of column names to sort by.

Selected rows are returned as an array of associative arrays, similar to calling the getAll method on a statement object for a custom query.

// select all columns and rows in the table, ordered by last name and then first name
$rows = $userTable->select([], [], ['lname', 'fname']);

// select first and last name columns where user_id is equal to 5
$rows = $userTable->select(['fname', 'lname'], ['user_id' => 5]);

// select all columns for an array of user IDs
$ids = [57, 239, 31, 54, 28];
$rows = $userTable->select([], ['user_id' => $ids]);

The insertOne method allows a single row to be inserted from an associative array. It returns an InsertResult object with getId and getAffected methods.

$userData = [
    'fname' => 'Donald',
    'lname' => 'Chamberlin'

$id = $userTable->insertOne($userData)->getId();

The insertBulk method makes it possible to bulk-insert multiple rows from an array. It returns a BulkInsertResult object with getIds, getAffected, and getQueryCount methods.

$userData = [
        'fname' => 'Grace',
        'lname' => 'Hopper'
        'fname' => 'Douglas',
        'lname' => 'Engelbart'
        'fname' => 'Margaret',
        'lname' => 'Hamilton'

$result = $userTable->insertBulk($userData);
$ids = $result->getIds(); // e.g. [64, 65, 66]
$affected = $result->getAffected(); // 3
$queries = $result->getQueryCount(); // 1

SQL Server allows a maximum of 1,000 rows to be inserted at a time, and limits individual queries to 2,099 or fewer bound parameters. MySQL supports a maximum of 65,536 bound parameters per query. These limits can be easily reached when attempting to bulk-insert hundreds or thousands of rows at a time. To avoid these limits, the insertBulk method automatically splits large bulk insert queries into batches to efficiently handle any number of rows (getQueryCount returns the number of required batches). The default limits (listed above) can be customized via the setMaxBoundParams and setMaxInsertRows option setters.

update and delete

The update method takes two arguments: an associative array of columns/values to update, and a WHERE array to filter which rows are updated.

The delete method takes a single WHERE array argument to filter the rows to delete.

Both methods return the number of affected rows.

// update the user with user_id 4
$newData = ['fname' => 'Raymond', 'lname' => 'Boyce'];
$userTable->update($newData, ['user_id' => 4]);

// delete users with IDs 1, 2, and 3
$userTable->delete(['user_id' => [1, 2, 3]]);


Call the begin method to start a transaction. prepare, execute, query and any of the shorthand methods can then be called as needed, before committing or rolling back the transaction with commit or rollback.

Other methods and options

The settings object passed to PeachySQL can be retrieved at any time using the getOptions method.

There is a MySQL-specific option to override the interval between successive auto-incremented IDs in the table (defaults to 1). PeachySQL uses this value to determine the array of insert IDs for bulk-inserts, since MySQL only provides the first insert ID.

$userTable->insertBulk($userData)->getIds(); // e.g. [67, 69, 71]


Theodore Brown