PHPackages                             jayrods/query-builder - 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. jayrods/query-builder

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

jayrods/query-builder
=====================

Simple query builder to ease SQL query writing

v1.1.6(3y ago)019GPL-3.0-or-laterPHP

Since Feb 25Pushed 3y ago1 watchersCompare

[ Source](https://github.com/Jadersonrilidio/querybuilder)[ Packagist](https://packagist.org/packages/jayrods/query-builder)[ RSS](/packages/jayrods-query-builder/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (6)Dependencies (3)Versions (8)Used By (0)

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

[](#querybuilder)

A lightweight, straight-forward and easy-to-use SQL query builder for DML and DQL queries.

 [ ![Package logo](./resources/img/logo.png) ](https://packagist.org/packages/jayrods/query-builder)

 [ ![Software License](https://camo.githubusercontent.com/1d269c1d24b6916474d9e9d44333268fb05b441e5932fd18514c7e0fe9378321/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f4a61646572736f6e72696c6964696f2f71756572796275696c6465723f7374796c653d666c61742d737175617265) ](LICENSE) [ ![Downloads](https://camo.githubusercontent.com/58d4cd634f041d66a117e98c5e5df5fd2f1b9ba60e6c98b5a547d8808fbc3cf5/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f646f776e6c6f6164732f4a61646572736f6e72696c6964696f2f71756572796275696c6465722f746f74616c3f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/jayrods/query-builder) [ ![Latest Version](https://camo.githubusercontent.com/4bb5e0bc2ce8221f9064545de2300c36aaa5bcc1afa496800214b394d7193d29/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f4a61646572736f6e72696c6964696f2f71756572796275696c6465723f7374796c653d666c61742d737175617265) ](https://github.com/Jadersonrilidio/querybuilder/releases) [ ![Code Size](https://camo.githubusercontent.com/a38a24d919a877b3ccccd2cd9e4a3a998163852d24f96d59ca84f52fb2f6eda9/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c616e6775616765732f636f64652d73697a652f4a61646572736f6e72696c6964696f2f71756572796275696c6465723f7374796c653d666c61742d737175617265) ](https://packagist.org/packages/jayrods/query-builder)

About
-----

[](#about)

**Writing SQL queries by hand is subject of great concern amongst developers!**It not just let your code 'dirty' (as some PHP purists might say) but also affects testability, simplicity and impose more work and time over development. With this in mind, this package comes in handy with a simple approach of wrapping SQL queries into PHP classes and methods, providing an abstraction with easy-to-use syntax and extra features to assert the queries are being written accordingly.

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

[](#installation)

Installation is super-easy via [Composer](https://getcomposer.org/):

```
$ composer require jayrods/query-builder
```

or add it by hand to your `composer.json` file.

Upgrading
---------

[](#upgrading)

We follow [semantic versioning](https://semver.org/), which means breaking changes may occur between major releases. We would introduce upgrading guides whenever major version releases becomes available [here](UPGRADING.md).

Getting Started
---------------

[](#getting-started)

Before start using the component, it's important to know how it is structured.

The QueryBuilder component is divided into 4 different use-cases, each representing one CRUD operation (Create, Read, Update and Delete). For simplicity sake, the component uses a QueryBuilder factory object to create all builder kinds with no trouble.

Follow bellow an example script using the component:

**Example 01**

```
use Jayrods\QueryBuilder\QueryBuilder;

// QueryBuilderFactory instance.
$builderFactory = new QueryBuilder();

// Create a SELECT queryBuilder use-case.
$builder = new $builderFactory->create(QueryBuilder::SELECT);

$selectQuery = $builder->selectFrom('users')
    ->column('uuid')
    ->columnAs('name', 'username')
    ->column('email')
    ->where('uuid', '=', 'uuid')
    ->build();

echo $selectQuery;
```

Output:

```
"SELECT users.uuid, users.name AS username, users.email FROM users WHERE uuid = :uuid"
```

**NOTE:** The `create()` method demands an argument informing which use-case to apply. In this case it is strongly recommended to use the available QueryBuilder object constants, as follow bellow:

```
QueryBuilder::DELETE = 'delete';
QueryBuilder::INSERT = 'insert';
QueryBuilder::SELECT = 'select';
QueryBuilder::UPDATE = 'update';
```

**NOTE:** By convention, the component works ONLY with parameterized values, following by the notation `:parameter` or `?`, as could be seen in [Parameterized options](https://github.com/Jadersonrilidio/querybuilder#parameterized-options).

**NOTE:** The `build()` method returns the built query and save it internaly, providing a `query()` method to retrieve the query whenever you whish. It also resets all other object's properties to default, enabling it to promptly start building another query if necessary.

```
echo $builder->query();
```

**ATTENTION!** Calling the `build()` method a second time will override the previously saved query.

**NOTE:** The component also enables partial construction of the query, providing more flexibility for the user:

```
$builder->selectFrom('users');
$builder->column('uuid');
$builder->column('email');
$builder->columnAs('name', 'username');
$builder->where('uuid', '=', 'uuid');

$query = $builder->build();

echo $query;
```

Output:

```
"SELECT users.uuid, users.name AS username, users.email FROM users WHERE uuid = :uuid"
```

Partial construction simplifies certain cases where a SQL query depends on certain conditions as in the example bellow:

```
$columns = ['uuid', 'name', 'email'];
$userUuid = 'example-user-uuid';

$builder->selectFrom('users');

foreach ($columns as $column) {
    $builder->column($column)
}

if (isset($userUuid)) {
    $builder->where('uuid', '=', 'uuid');
}

$query = $builder->build();

echo $query;
```

Output:

```
"SELECT users.uuid, users.name, users.email FROM users WHERE uuid = :uuid"
```

**NOTE:** It is important to say that **EACH USE-CASE INSTANCE HAS ITS OWN SET OF METHODS**, that could differ from each other either if the methods have the same name. In the next examples you could notice the difference of called methods for each use-case:

**Example 02**

```
use Jayrods\QueryBuilder\QueryBuilder;

// QueryBuilderFactory instance.
$builderFactory = new QueryBuilder();

// Create a INSERT queryBuilder use-case.
$builder = new $builderFactory->create(QueryBuilder::INSERT);

$insertQuery = $builder->insertInto('users')
    ->column('name')
    ->column('email')
    ->build();

echo $insertQuery;
```

Output:

```
"INSERT INTO users (name, email) VALUES (:name, :email)"
```

**Example 03**

```
use Jayrods\QueryBuilder\QueryBuilder;

// QueryBuilderFactory instance.
$builderFactory = new QueryBuilder();

// Create a DELETE queryBuilder use-case.
$builder = new $builderFactory->create(QueryBuilder::DELETE);

$deleteQuery = $builder->delete('users')
    ->where('uuid', '=')
    ->or('uuid', '=', 'param2')
    ->build();

echo $deleteQuery;
```

Output:

```
"DELETE FROM users WHERE uuid = :uuid OR uuid = :param2"
```

**Example 04**

```
use Jayrods\QueryBuilder\QueryBuilder;

// QueryBuilderFactory instance.
$builderFactory = new QueryBuilder();

// Create a UPDATE queryBuilder use-case.
$builder = new $builderFactory->create(QueryBuilder::UPDATE);

$deleteQuery = $builder->update('users')
    ->column('name')
    ->column('email')
    ->where('uuid', '=')
    ->build();

echo $deleteQuery;
```

Output:

```
"UPDATE users SET name = :name, email = :email WHERE uuid = :uuid"
```

More detailed explanation for each use-case could be seen on the sections bellow:

- [Building DELETE Queries](https://github.com/Jadersonrilidio/querybuilder#delete-queries).
- [Building INSERT Queries](https://github.com/Jadersonrilidio/querybuilder#insert-queries).
- [Building SELECT Queries](https://github.com/Jadersonrilidio/querybuilder#select-queries).
- [Building UPDATE Queries](https://github.com/Jadersonrilidio/querybuilder#update-queries).

### DELETE Queries

[](#delete-queries)

#### Methods

[](#methods)

```
// Start building DELETE query.
DeleteQueryBuilder::delete(string $table): self

// Start WHERE clause.
DeleteQueryBuilder::where(string $column, string $operator, ?string $binder = null): self

// Start WHERE NOT clause.
DeleteQueryBuilder::whereNot(string $column, string $operator, ?string $binder = null): self

// Start WHERE IN clause.
DeleteQueryBuilder::whereIn(string $column, string $subquery): self

// Start WHERE NOT IN clause.
DeleteQueryBuilder::whereNotIn(string $column, string $subquery): self

// Start WHERE BETWEEN clause.
DeleteQueryBuilder::whereBetween(string $column, ?string $left = null, ?string $right = null): self

// Start WHERE NOT BETWEEN clause.
DeleteQueryBuilder::whereNotBetween(string $column, ?string $left = null, ?string $right = null): self

// Add AND clause to conditions.
DeleteQueryBuilder::and(string $column, string $operator, ?string $binder = null): self

// Add AND NOT clause to conditions.
DeleteQueryBuilder::andNot(string $column, string $operator, ?string $binder = null): self

// Add AND BETWEEN clause to conditions.
DeleteQueryBuilder::andBetween(string $column, ?string $left = null, ?string $right = null): self

// Add AND NOT BETWEEN clause to conditions.
DeleteQueryBuilder::andNotBetween(string $column, ?string $left = null, ?string $right = null): self

// Add OR clause to conditions.
DeleteQueryBuilder::or(string $column, string $operator, ?string $binder = null): self

// Add OR NOT clause to conditions.
DeleteQueryBuilder::orNot(string $column, string $operator, ?string $binder = null): self

// Add OR BETWEEN clause to conditions.
DeleteQueryBuilder::orBetween(string $column, ?string $left = null, ?string $right = null): self

// Add OR NOT BETWEEN clause to conditions.
DeleteQueryBuilder::orNotBetween(string $column, ?string $left = null, ?string $right = null): self

// Build the query and set it to the query attribute.
DeleteQueryBuilder::build(): string

// Return the last built query or empty string.
DeleteQueryBuilder::query(): string

// Return array with used parameterized names acresced by ':' notation.
DeleteQueryBuilder::getBindParams(): array
```

#### Examples

[](#examples)

**Example 01**

```
$builderFactory = new QueryBuilder();
$builder = $builderFactory->create(QueryBuilder::DELETE);

$builder->delete('users')
    ->where('birth_date', 'create(QueryBuilder::SELECT);

$builder->selectFrom('users')
    ->columnAs('name', 'username')
    ->columnAs('email', 'useremail')
    ->columnAs('area_code', 'phonearea', 'phones')
    ->columnAs('number', 'phonenumber', 'phones')
    ->innerJoin('phones', 'user_uuid', '=', 'uuid')
    ->where('uuid', '=', 'uuid')
    ->build();

echo $builder->query();
```

Output:

```
"SELECT
    users.name AS username, users.email AS useremail,
    phones.area_code AS phonearea, phones.number AS phonenumber
    FROM users
    INNER JOIN phones ON phones.user_uuid = users.uuid
    WHERE uuid = :uuid"
```

**Example 03**

```
$builderFactory = new QueryBuilder();
$builder = $builderFactory->create(QueryBuilder::SELECT);

$builder->selectFrom('users')
    ->column('uuid')
    ->column('name')
    ->column('email')
    ->orderBy('name')
    ->asc()
    ->limit(20)
    ->build();

echo $builder->query();
```

Output:

```
"SELECT users.uuid, users.name, users.email FROM users ORDER BY users.name ASC LIMIT 20;
```

### UPDATE Queries

[](#update-queries)

#### Methods

[](#methods-3)

```
// Start building UPDATE query.
UpdateQueryBuilder::update(string $table): self

// Add column to be updated with respective binder name.
UpdateQueryBuilder::column(string $column, ?string $binder = null): self

// Start WHERE clause.
UpdateQueryBuilder::where(string $column, string $operator, ?string $binder = null): self

// Start WHERE NOT clause.
UpdateQueryBuilder::whereNot(string $column, string $operator, ?string $binder = null): self

// Start WHERE IN clause.
UpdateQueryBuilder::whereIn(string $column, string $subquery): self

// Start WHERE NOT IN clause.
UpdateQueryBuilder::whereNotIn(string $column, string $subquery): self

// Start WHERE BETWEEN clause.
UpdateQueryBuilder::whereBetween(string $column, ?string $left = null, ?string $right = null): self

// Start WHERE NOT BETWEEN clause.
UpdateQueryBuilder::whereNotBetween(string $column, ?string $left = null, ?string $right = null): self

// Add AND clause to conditions.
UpdateQueryBuilder::and(string $column, string $operator, ?string $binder = null): self

// Add AND NOT clause to conditions.
UpdateQueryBuilder::andNot(string $column, string $operator, ?string $binder = null): self

// Add AND BETWEEN clause to conditions.
UpdateQueryBuilder::andBetween(string $column, ?string $left = null, ?string $right = null): self

// Add AND NOT BETWEEN clause to conditions.
UpdateQueryBuilder::andNotBetween(string $column, ?string $left = null, ?string $right = null): self

// Add OR clause to conditions.
UpdateQueryBuilder::or(string $column, string $operator, ?string $binder = null): self

// Add OR NOT clause to conditions.
UpdateQueryBuilder::orNot(string $column, string $operator, ?string $binder = null): self

// Add OR BETWEEN clause to conditions.
UpdateQueryBuilder::orBetween(string $column, ?string $left = null, ?string $right = null): self

// Add OR NOT BETWEEN clause to conditions.
UpdateQueryBuilder::orNotBetween(string $column, ?string $left = null, ?string $right = null): self

// Build the query and set it to the query attribute.
UpdateQueryBuilder::build(): string

// Return the last built query or empty string.
UpdateQueryBuilder::query(): string

// Return array with used parameterized names acresced by ':' notation.
UpdateQueryBuilder::getBindParams(): array
```

#### Examples

[](#examples-3)

**Example 01**

```
$builderFactory = new QueryBuilder();
$builder = $builderFactory->create(QueryBuilder::UPDATE);

$builder->update('users')
    ->column('name')
    ->column('email')
    ->where('uuid', '=')
    ->build();

echo $builder->query();
```

Output:

```
"UPDATE users SET name = :name, email = :email WHERE uuid = :uuid"
```

Advanced Options
----------------

[](#advanced-options)

The QueryBuilder component also provides features to help assert the correct building of a query, by throwing errors on inconsistency, echoing console warnings on inconsistency and ignoring unexpected on wrong build methods calling.

The principal helper feature is the Constrained QueryBuilder Mode [See Constrained Mode](https://github.com/Jadersonrilidio/querybuilder#constrained-mode). It's major function is to ignore missplaced build methods to avoid wrong query writing, and also allows the component to inform the user throught Exceptions thrown or console messages echoing during runtime.

All different modes could be enabled using Environment variables or config file settings, as could be seen [Here - Environment Variables](https://github.com/Jadersonrilidio/querybuilder#environment-variables-options)and [Here - Configuration File](https://github.com/Jadersonrilidio/querybuilder#config-file), respectively

### Constrained Mode

[](#constrained-mode)

The constrained mode's major function is to ignore missplaced build methods, avoiding wrong query writing. It also allows the component to inform the errors occuried and the action taken throught Exceptions thrown or console messages echoing during runtime.

The constrained mode could be enabled/disabled by two ways:

First, setting the environment variable `QB_ENABLE_CONSTRAINED_MODE` in a `.env` file;

Second, overriding the config file `ENABLE_CONSTRAINED_MODE` param. [More about config file here](https://github.com/Jadersonrilidio/querybuilder#config-file)

**NOTE:** By default, the constrained mode is set to true.

```
QB_ENABLE_CONSTRAINED_MODE=true
```

With the constrained mode on (`QB_ENABLE_CONSTRAINED_MODE=true`), the user have two more available options:

Enable\\disable Constrained mode to throw an Exception on fail, throught the env variable `QB_FAIL_ON_WRONG_METHOD_CALL`;

Enable\\disable Constrained mode to echo message on fail, throught the env variable `QB_ECHO_WARNINGS_ON_WRONG_METHOD_CALL`;

**NOTE:** By default:

```
QB_FAIL_ON_WRONG_METHOD_CALL=false
QB_ECHO_WARNINGS_ON_WRONG_METHOD_CALL=true
```

**IMPORTANT!** As the constrained mode is used to assert the right construction of the query, we recommend to use it only for development, and disable the constrained mode for production to make the component more performatic.

### Environment Variables Options

[](#environment-variables-options)

Follow bellow all the available environment variables with their default value:

```
QB_ENABLE_CONSTRAINED_MODE=true
QB_FAIL_ON_WRONG_METHOD_CALL=false
QB_ECHO_WARNINGS_ON_WRONG_METHOD_CALL=true
QB_PARAMETERIZED_MODE=true
QB_PARAMETERIZED_MODE_FAIL_ON_ERROR=false
QB_PARAMETERIZED_MODE_ECHO_WARNINGS_ON_ERROR=true
```

### Parameterized Options

[](#parameterized-options)

```
QB_PARAMETERIZED_MODE=true
QB_PARAMETERIZED_MODE_FAIL_ON_ERROR=false
QB_PARAMETERIZED_MODE_ECHO_WARNINGS_ON_ERROR=true
```

### Config File

[](#config-file)

In addition, it is possible to set all component's options throught a `queryBuilderConfig.php` file. By default, the component uses its config file available in the package `./config` folder, however there is a possibility to puslish such file in the root `./config` folder, or even in a user-defined directory [See](https://github.com/Jadersonrilidio/querybuilder#publishing-config-file).

To use a config file in a user-defined directory, it makes necessary to inform the user-defined path to the QueryBuilder object, like the example bellow:

```
$configFilePath = dirname(__DIR__) . '/path/to/file/queryBuilderConfig.php';

$builderFactory = new QueryBuilder($configFilePath);
```

#### Publishing Config File

[](#publishing-config-file)

The component make available a bin script to publish correctly the `queryBuilderConfig.php`file. The user can puslish the config file by typing the following commands at the console:

```
php vendor/bin/qb_publish_config
```

Without argument, attempt to create config file on `./config/` folder, if exists

```
php vendor/bin/qb_publish_config
```

With argument, attempt to create on the passed folder, if exists

```
php vendor/bin/qb_publish_config ./path/to/folder/
```

Contributing
------------

[](#contributing)

We appreciate the kindness of any developer willing to contribute to this project to make it complete enough to real-project use, by suggesting or adding new features, covering vulnerability and other nature issues. If you are willing to contribute to this project, please send an email to [jayrods](jaderson.rodrigues@yahoo.com).

Security
--------

[](#security)

If you discover a security vulnerability within this package, please report the issue or send an email to [jayrods](jaderson.rodrigues@yahoo.com). All security vulnerabilities will be promptly addressed. We appreciate your concern.

License
-------

[](#license)

QueryBuilder is licensed under [The GPL V3.0 License](LICENSE).

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity50

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

Total

7

Last Release

1172d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6b037a6fa6bb0a2dd2091095e594838dd47d2b8dec486f7ee1e7e9d5c44c62fc?d=identicon)[Jadersonrilidio](/maintainers/Jadersonrilidio)

---

Top Contributors

[![Jadersonrilidio](https://avatars.githubusercontent.com/u/78319352?v=4)](https://github.com/Jadersonrilidio "Jadersonrilidio (43 commits)")

---

Tags

sqlqueryquerybuilderjayrods

###  Code Quality

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/jayrods-query-builder/health.svg)

```
[![Health](https://phpackages.com/badges/jayrods-query-builder/health.svg)](https://phpackages.com/packages/jayrods-query-builder)
```

###  Alternatives

[rennokki/laravel-eloquent-query-cache

Adding cache on your Laravel Eloquent queries' results is now a breeze.

1.1k4.0M14](/packages/rennokki-laravel-eloquent-query-cache)[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)[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11320.2M21](/packages/anourvalar-eloquent-serialize)[nilportugues/sql-query-builder

An elegant lightweight and efficient SQL QueryInterface BuilderInterface supporting bindings and complicated query generation.

425239.4k6](/packages/nilportugues-sql-query-builder)[supliu/laravel-query-monitor

Laravel Query Monitor

287111.9k](/packages/supliu-laravel-query-monitor)[illuminated/db-profiler

Database Profiler for Laravel Web and Console Applications.

168237.4k](/packages/illuminated-db-profiler)

PHPackages © 2026

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