PHP code example of rain1 / condition-builder

1. Go to this page and download the library: Download rain1/condition-builder 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/ */

    

rain1 / condition-builder example snippets




ain1\ConditionBuilder\ConditionBuilder;
use rain1\ConditionBuilder\Operator\IsEqual;
use rain1\ConditionBuilder\Operator\IsLess;

$condition = new ConditionBuilder(ConditionBuilder::MODE_AND);

$condition->append(
	new IsEqual("id", 3), // id = ? AND
	new IsLess("priority", 100), // priority < ? AND
	new IsEqual("myCol", [1,2,3]), // myCol IN (?,?,?)
	new IsEqual("anotherCol", null), // it will be ignored because null value
	(new ConditionBuilder(ConditionBuilder::MODE_OR))
		->append(
			new IsEqual("col1", 3), // col1 = ? OR
			new IsEqual("someflag", 0) // someflag = ?
		)
);

$query =  "SELECT * FROM myTable WHERE $condition";

echo $query."\n";
print_r($condition()); // shortcut of $condition->values() it returns an array with all values

//$res = $pdo->prepare($query)->execute($condition->values());



function filterUser(array $filters = []) : array
{
    $defaults = [
        'id'                     => null,
        'banned'                 => null,
        'last_login_range_start' => null,
        'last_login_range_end'   => null,
        'email'                  => null,
    ];
    $filters  = $filters + $defaults;

    $condition = new ConditionBuilder(ConditionBuilder::MODE_AND);

    $condition->append(
        new IsEqual('id', $filters['id']),
        new IsEqual('email', $filters['email']),
        new IsEqual('banned', $filters['banned']),
        new IsBetween("last_login", $filters["last_login_range_start"], $filters["last_login_range_end"])
    );
    
    return YourMysqlLibrary::query("SELECT * FROM user WHERE $condition", $condition());
}

$rows = filterUser([
    'id' => [1,2,3]
]); // users with id 1,2 or 3 

$rows = filterUser([
    'last_login_range_start' => date("Y-m-d 00:00:00", "yesterday"),
    'banned' => 0
]); // users not banned and logged yesterday or today

$rows = filterUser([
    'last_login_range_start' => "2021-01-01",
    'last_login_range_end' => "2021-01-31",
    'banned' => 1
]); // users actually banned and last seen in Jan 2021

$rows = filterUser([
    'email' => "[email protected]"
]); // user with specified email
// and so on



SELECT * FROM myTable WHERE (id = ? AND priority < ? AND myCol IN (?,?,?) AND (col1 = ? OR someflag = ?))
Array
(
    [0] => 3
    [1] => 100
    [2] => 1
    [3] => 2
    [4] => 3
    [5] => 3
    [6] => 0
)