简体   繁体   中英

how to pass dynamically value to where condition if the specific value exists in array?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM