PHP code example of gajus / klaus

1. Go to this page and download the library: Download gajus/klaus library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gajus / klaus example snippets


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

$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' => '=']
            ]
        ]
    ]
]

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

/**
 * @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);

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

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

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

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

$sth->execute($input);

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

$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());

// ..