Reputation: 1575
I'm sending values from ajax to PHP as an associative array, depending on some values i should include statement into WHERE
statement. For example i have this kind of array
Array
(
[project_name] => Riverside
[property_type] => For Rent
[rooms] => default
)
if rooms value is equal to default, i should not use WHERE statement for rooms so it looks like this.
$sql = SELECT Property_Type, Property_Name, Rooms from appartment
WHERE Project_Name = :project_name AND
Property_Type = :property_type;
in case if array rooms is equal to 2, sql statement should look like this
$sql = SELECT Property_Type, Property_Name, Rooms from appartment
WHERE Project_Name = :project_name AND
Property_Type = :property_type AND Rooms = 2;
I don't want to write to separate sql statements, since this will apply as well for project_name
and project_type if the values is All projects
it should not use Project_Name
in Where statement.
Can anyone explain how can i achieve this?
Upvotes: 0
Views: 115
Reputation: 43441
Dynamically build your query:
$sql = 'SELECT Property_Type, Property_Name, Rooms from appartment';
$where = [];
$params = [];
foreach ($_GET['WhereConditions'] as $key => $value) {
switch($key) {
case 'rooms':
if ($value == 2) {
$where[] = "`Rooms` = :roomsCount";
$params[':roomsCount'] = 2;
}
break;
...
}
}
if (!empty($where)) {
$sql .= ' WHERE '.implode('AND', $where);
}
$db->prepare($sql)->fetchAll($params);
Upvotes: 1