Im trying to create a dynamic WHERE clause builder with PHP OOP. And Im not sure what Im doing is right.
So I created a class named QueryBuilder where I have a private property named $filters (this is an array property for store both keys and values for filters) and two methods:
1, addFilter() -> This is for adding "filters" to the query
2, getFilters() -> This is for getting the WHERE clause string and the params for PDO execute()
Here is my code:
class QueryBuilder {
private array $filters;
public function addFilter(array $filterDetails): void
{
$this->filters[] = $filterDetails;
}
public function getFilters(): array
{
$whereClause = " WHERE 1";
if (!empty($this->filters)) {
foreach ($this->filters as $filter) {
$whereClause .= " AND (" . $filter["searchKey"] . " " . $filter["operator"] . " :" . $filter["searchKey"] . ")";
$params[":" . $filter["searchKey"]] = $filter["searchValue"];
}
return ["whereClause" => $whereClause,
"params" => $params];
}
return ["whereClause" => $whereClause,
"params" => null];
}
}
And this is how I run it:
$QueryBuilder = new QueryBuilder();
$sql = "SELECT * FROM mytable";
$name = "Test Name";
$age = 12;
$QueryBuilder->addFilter(["operator" => "LIKE",
"searchKey" => "name",
"searchValue" => $name]);
$QueryBuilder->addFilter(["operator" => "=",
"searchKey" => "age",
"searchValue" => $age]);
$whereClause = $QueryBuilder->getFilters();
echo $sql . $whereClause["whereClause"];
echo "</br>";
echo "<pre>";
print_r($whereClause["params"]);
echo "</pre>";
The results seems to be fine:
SELECT * FROM mytable WHERE 1 AND (name LIKE :name) AND (age = :age)
Array
(
[:name] => Test Name
[:age] => 12
)
But now Im trying to create a WHERE clause where is a BETWEEN operator and I don't have any idea how can I implement into this code.
Anyway what do you think this is a good approach to create a query (WHERE CLAUSE) builder? Or should I make some modifications to the code?
Thank you!