PHPackages                             gajus/klaus - 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. gajus/klaus

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

gajus/klaus
===========

User input interpreter for constructing SQL WHERE clause.

0.1.0(12y ago)2501BSD-3-ClausePHPPHP &gt;=5.5

Since Apr 25Pushed 12y ago1 watchersCompare

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

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

Klaus
=====

[](#klaus)

[![Build Status](https://camo.githubusercontent.com/2d236c6c4dd18e3b818aa10d139ea25ca68a40f88e45962006f331bb4b5b3990/68747470733a2f2f7472617669732d63692e6f72672f67616a75732f6b6c6175732e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/gajus/klaus)[![Coverage Status](https://camo.githubusercontent.com/d72856f3e444b1d651ad558db59cc9a4d48d795ec1955ce3f5b6d71647c6788c/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f67616a75732f6b6c6175732f62616467652e706e673f6272616e63683d6d6173746572)](https://coveralls.io/r/gajus/klaus?branch=master)[![Latest Stable Version](https://camo.githubusercontent.com/4d091c01ffc9801201b4219ecd543f2cc507f52c8fe9654ba5ded5ae54ecf92f/68747470733a2f2f706f7365722e707567782e6f72672f67616a75732f6b6c6175732f76657273696f6e2e706e67)](https://packagist.org/packages/gajus/klaus)[![License](https://camo.githubusercontent.com/8b7b5f9fc4f7c2c7f660202dabba99b364ea65bfea186d67ce4e86a2a20e9fc9/68747470733a2f2f706f7365722e707567782e6f72672f67616a75732f6b6c6175732f6c6963656e73652e706e67)](https://packagist.org/packages/gajus/klaus)

User input interpreter for constructing SQL `WHERE` clause. Klaus can build complex `WHERE` clauses of variable depth and with different grouping conditions.

Documentation
-------------

[](#documentation)

### Preparing Query

[](#preparing-query)

Raw query consists of the grouping operator definition (`AND` or `OR`) and condition. There are two types of conditions:

#### Comparison Condition

[](#comparison-condition)

Comparison consists of user input name, value and the comparison operator, e.g.

```
[
    'name' => 'foo_name', // User input name
    'value' => '1', // User input value
    'operator' => '=' // Condition operator
]
```

#### Group Condition

[](#group-condition)

The condition itself can define new group, e.g.

```
$query = [
    'group' => 'AND',
    'condition' => [
        ['name' => 'foo_name', 'value' => '1', 'operator' => '='],
        ['name' => 'bar_name', 'value' => '2', 'operator' => '='],
        [
            'group' => 'OR',
            'condition' => [
                ['name' => 'foo_name', 'value' => '1', 'operator' => '='],
                ['name' => 'bar_name', 'value' => '2', 'operator' => '=']
            ]
        ]
    ]
]
```

A complete query must include at least one group and at least one comparison operator.

### Mapping Using Input

[](#mapping-using-input)

Mapping is used to restrict columns that can be included in the query, as well as to provide support for columns that depend on alias or even more complicated constructs.

```
SELECT
    `f1`.`name`,
    `b1`.`name`
FROM
    `foo` `f1`
INNER JOIN
    `bar` `b1`
ON
    [..]
```

In the above example, you need to define relation between the parameter name that you are using in the query and the column name in the SQL query, e.g.

```
$map = [
    'foo_name' => '`f1`.`name`',
    'bar_name' => '`b1`.`name`'
];
```

### Buildng the `WHERE` Clause

[](#buildng-the-where-clause)

The preceeding examples explain how to prepare data for the `Where` constructor.

```
/**
 * @param array $query
 * @param array $map Map input name to the aliased column in the SQL query, e.g. ['name' => '`p1`.`name`'].
 */
$where = new \Gajus\Klaus\Where($query, $map);
```

We are going to use the SQL from the previous example to construct a prepared statement and execute it.

The `WHERE` clause itself is generated using `getClause` method:

```
/**
 * @return string SQL WHERE clause representng the query.
 */
$where->getClause();
```

If query does not produce a condition, then `getClause` will always return `1=1`, e.g.

```
$sql = "
SELECT
    `f1`.`name`,
    `b1`.`name`
FROM
    `foo` `f1`
INNER JOIN
    `bar` `b1`
ON
    [..]
WHERE
    {$where->getClause()}
    ";
```

In the above example, `$sql` is:

```
SELECT
    `f1`.`name`,
    `b1`.`name`
FROM
    `foo` `f1`
INNER JOIN
    `bar` `b1`
ON
    [..]
WHERE
    `f1`.`name` = :foo_name_0 AND
    `b1`.`name` = :bar_name_1 AND
        (
            `f1`.`name` = :foo_name_2 OR
            `b1`.`name` = :bar_name_3
        )
```

To execute the query, you have to build [PDOStatement](http://www.php.net/manual/en/class.pdostatement.php), e.g.

```
$sth = $db->prepare($sql);
```

and execute it using the input data:

```
/**
 * @return array Input mapped to the prepared statement bindings present in the WHERE clause.
 */
$input = $where->getInput();

$sth->execute($input);
```

In the above example, `$input` is equal to:

```
[
    'foo_name_0' => '1',
    'bar_name_1' => '2',
    'foo_name_2' => '1',
    'bar_name_3' => '2',
]
```

### Input Template

[](#input-template)

For basic search you can use `Gajus\Klaus\Where::queryTemplate`.

- Basic query template takes name =&gt; value pairs and converts them to `WHERE` clause grouped using `AND`.
- Empty values are discarded.
- Values begning with `%` will use `LIKE` comparison.
- Values endding with `%` will use `LIKE` comparison.
- Values that do not contain `%` or where `%` is not at the begining or end of the query will use `=` comparison.

#### Example

[](#example)

```
$query = \Gajus\Klaus\Where::queryTemplate(['foo' => 'bar', 'baz' => 'qux%']);

// $query is now eq. to:

$query = [
    'group' => 'AND',
    'condition' => [
        ['name' => 'foo', 'value' => 'bar', 'operator' => '='],
        ['name' => 'baz', 'value' => 'qux%', 'operator' => 'LIKE']
    ]
];

// Which you then pass to the Where constructor.

$where = new \Gajus\Klaus\Where($query, ['foo' => '`foo`', 'baz' => '`baz`']);

$sth = $db->prepare("SELECT `foo`, `baz` FROM `quux` WHERE {$where->getClause()}");
$sth->execute($where->getInput());

// ..
```

Alternatives
------------

[](#alternatives)

[elasticsearch](http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html) (ES) provides an API with a query DSL. The only downside of using ES is that it requires data dupliction.

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity48

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

Unknown

Total

1

Last Release

4399d ago

### Community

Maintainers

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

---

Top Contributors

[![gajus](https://avatars.githubusercontent.com/u/973543?v=4)](https://github.com/gajus "gajus (26 commits)")

---

Tags

querywhereclause

### Embed Badge

![Health badge](/badges/gajus-klaus/health.svg)

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

###  Alternatives

[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[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)[envms/fluentpdo

FluentPDO is a quick and light PHP library for rapid query building. It features a smart join builder, which automatically creates table joins.

925511.7k13](/packages/envms-fluentpdo)[anourvalar/eloquent-serialize

Laravel Query Builder (Eloquent) serialization

11320.2M21](/packages/anourvalar-eloquent-serialize)[bvanhoekelen/performance

PHP performance tool analyser your script on time, memory usage and db query. Support Laravel and Composer for web, web console and command line interfaces.

521774.3k4](/packages/bvanhoekelen-performance)

PHPackages © 2026

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