PHPackages                             olajoscs/querybuilder - 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. olajoscs/querybuilder

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

olajoscs/querybuilder
=====================

A basic query builder for relational databases.

1.0.7(8y ago)0100[2 issues](https://github.com/olajoscs/QueryBuilder/issues)1MITPHPPHP &gt;=5.5.0

Since Nov 12Pushed 8y ago1 watchersCompare

[ Source](https://github.com/olajoscs/QueryBuilder)[ Packagist](https://packagist.org/packages/olajoscs/querybuilder)[ Docs](https://github.com/olajoscs/QueryBuilder)[ RSS](/packages/olajoscs-querybuilder/feed)WikiDiscussions master Synced today

READMEChangelog (9)Dependencies (2)Versions (10)Used By (1)

[![Build Status](https://camo.githubusercontent.com/cc88d3c2a7c9b6c31256331c901f1456203554cc45866e8c2d2b47b2f0938fd0/68747470733a2f2f7472617669732d63692e6f72672f6f6c616a6f7363732f51756572794275696c6465722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/olajoscs/QueryBuilder)[![Latest Stable Version](https://camo.githubusercontent.com/1f218e1fb0d0e1f962602fca528de12a992994e455edf6ce95ae50e5ba8781f6/68747470733a2f2f706f7365722e707567782e6f72672f6f6c616a6f7363732f71756572796275696c6465722f762f737461626c65)](https://packagist.org/packages/olajoscs/querybuilder)

QueryBuilder
============

[](#querybuilder)

A simple query builder for relational databases, currently working with:

- MySQL,
- PostgreSQL,
- SQLite.

100% of the code is unit tested.

Contains the 4 basic (CRUD) operations with transaction handling.

Minimum requirements: PHP 5.5+ with any of the databases above.

Creating the connection
=======================

[](#creating-the-connection)

The Connection class extends the built-in PDO class. It is the starting point of creating statements. Create a new instance based on the database type you are using, and give it to your DI container trait it as a singleton. The constructor is the same as the one in the PDO class.

```
  $myDIContainer->singleton('connection', function() {
    // Create an own config object, which extends the ConnectionConfig abstract class, or implements the Config interface
    $configArray = include(..);
    $config = new Config($configArray);

    // Create the PDO by the config object
    $pdo = new \OlajosCs\QueryBuilder\PDO($config);

    // Create a connection factory
    $connectionFactory = new \OlajosCs\QueryBuilder\ConnectionFactory();

    // Use the ConnectionFactory to create the Connection object by the PDO
    $connection = $connectionFactory->create($pdo);

    return $connection;
  });
```

Starting from Connection
========================

[](#starting-from-connection)

There are 4 statements (Select, Update, Insert, Delete), which have own methods to create. All the statements has an execute method, which executes the built query, then returns the PDOStatement object.

Transaction
-----------

[](#transaction)

Transaction can be used with a callback function. In case of any exception all changes are rollbacked.

```
  $connection->transaction(function() use ($connection) {
    $connection->get(...);
  });
```

Basic select syntax
-------------------

[](#basic-select-syntax)

The syntax of building a select statmenet is similar to do it in SQL.

```
  $connection
    ->select(['field', 'list'])
    ->from('table_name')
    ->where('field', '=', $value)
    ->groupBy('field')
    ->orderBy('field')
    ->get();
```

### List of get.... methods

[](#list-of-get-methods)

- get(): Returns an array of stdClasses.
- getAsClasses(string $className, array $constructorParameter): Returns an array of explicit object.
- getOne(): Returns only one stdClass. If multiple rows would be returned, or there are no rows to return, it throws exception.
- getOneClass(string $className, array $constructorParameter): Returns only one explicit object. If multiple rows would be returned, or there are no rows to return, it throws exception.
- getOneField(string $fieldName): Returns only one field of the row. If the field is not found, exception is thrown.
- getList(string $fieldName): Returns a list of the specified field from the rows. IF the field is not found, exception is thrown.
- getWithKey(string $keyField): Returns the an array of stdClasses. The key of the elements are the current value of the $keyField variable.
- getClassesWithKey(string $className, array $constructorParameters, string $keyField): Returns an array of explicit objects. The key of the elements are the current value of the $keyField variable.

Basic update syntax
-------------------

[](#basic-update-syntax)

Update syntax is similar as seen in SQL.

The query is executed only when the execute() method is called.

```
  $connection
    ->update('table_name')
    ->set(
      [
        'value1' => 1,
        'value2' => 2
      ]
    )
    ->where('id', '=', 1)
    ->execute();
```

Basic insert syntax
-------------------

[](#basic-insert-syntax)

Insert syntax is similar as seen in SQL.

The query is executed only when the execute() method is called.

```
  $connection
    ->insert(
      [
        'field1' => 1,
        'field2' => 2
      ]
    )
    ->into('table_name')
    ->execute();
  // OR
  $connection
    ->insert()
    ->into('table_name')
    ->values(
      [
        'field1' => 1,
        'field2' => 2
      ]
    )
    ->execute();
```

Multiple rows for insert statement is also supported, these can be added in a 2 dimensional array.

```
  $connection
    ->insert(
      [
        [
          'field1' => 1,
          'field2' => 2
        ],
        [
          'field1' => 3,
          'field2' => 4
        ],
      ]
    )
    ->into('table_name')
    ->execute();
```

Basic delete syntax
-------------------

[](#basic-delete-syntax)

Delete syntax is similar as seen in SQL.

The query is executed only when the execute() method is called.

```
  $connection
    ->delete()
    ->from('table_name')
    ->where('id', '=', 1)
    ->execute();
```

Raw expressions
---------------

[](#raw-expressions)

RawExpression object can be used when any expression is needed, but the querybuilder is not able to handle it. This can be used in select and where methods.

```
  // for MySQL
  $connection
    ->select($connection->createRawExpression('count(1) as counter'))
    ->from('tests')
    ->getOneField('counter');

  $connection
    ->select() // empty means *
    ->from('tests')
    ->where($connection->createRawExpression('select count....... = 1')
    ->get();
```

Where clauses
-------------

[](#where-clauses)

In Select, Update and Delete statements where clauses can be used. All these statements have the following methods regarding where either with "and" connector (normal methods) or "or" connector, with a where...Or method.

### Where... methods

[](#where-methods)

- where(string $field, string $operator, mixed $value): Basic where, field {&lt;&gt;!=} value.
- whereIn(string $field, array $values): Where field in (value1, value2).
- whereNotIn(string $field, array $values): Where field not in (value1, value2).
- whereBetween(string $field, mixed $min, mixed $max): Where field between min and max.
- whereNull(string $field): Where field is null.
- whereNotNull(string $field): Where field is not null.
- whereRaw(RawExpression('where ...')): Where clause is placed directly into the query.

###  Health Score

28

—

LowBetter than 52% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity64

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

Recently: every ~66 days

Total

9

Last Release

3078d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/47fabfd1980b2e2628bca1a93867e391932a1a5fe59ff3131dd3b59b44b031ad?d=identicon)[olajoscs](/maintainers/olajoscs)

---

Top Contributors

[![olajoscs](https://avatars.githubusercontent.com/u/6685631?v=4)](https://github.com/olajoscs "olajoscs (84 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/olajoscs-querybuilder/health.svg)

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

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k116.5M113](/packages/jdorn-sql-formatter)[propel/propel1

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

8351.6M87](/packages/propel-propel1)[pgvector/pgvector

pgvector support for PHP

198628.3k10](/packages/pgvector-pgvector)

PHPackages © 2026

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