K
K
kostya17042020-12-28 18:22:00
PHP
kostya1704, 2020-12-28 18:22:00

How to correctly form a data request by parameter filter?

5fe9f3baf1b63962814458.png
There is a request to a DB.

$poisks = DB::select("select * from items where brand = '$brand' && fuel_type IN('$fuel_type') && location = '$location' && body_type IN('$body_type') && year BETWEEN '$year_from' AND '$year_to' && price BETWEEN '$price_from' AND '$price_to' && engine BETWEEN '$engine_from' AND '$engine_to'");

When choosing from each select block or checkboxes, the query works.
What to do when one or more selects or block of checkboxes, for example "Type of fuel" or "Brand" are not selected, and , accordingly, $brand is empty. How to ignore the parameter in the query when the variable is empty? $brand = $_POST['brand']; "brand" => ""

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
CarfikDK, 2020-12-28
@kostya1704

Make a variable which will add optional parameters if something happens.
For example:

$where = '';
if($_POST['brand']){
    $where .= ' brand = ' . $_POST['brand'];
}

$poisks = DB::select("select * from items where ". $where ." && fuel_type IN('$fuel_type') && location = '$location' && body_type IN('$body_type') && year BETWEEN '$year_from' AND '$year_to' && price BETWEEN '$price_from' AND '$price_to' && engine BETWEEN '$engine_from' AND '$engine_to'");

There is a jamb with the fact that there must be at least some kind of require parameter so that you can immediately enter AND for the $where variable and expand this variable through other checks. It’s just that I don’t know how to check whether this condition will be the first and whether AND should be added, or leave WHERE
Not that for good, but for it to work:
$where = '';
if($_POST['brand']){
    $where .= 'AND brand = ' . $_POST['brand'];
}
if($_POST['fuel_type']){
    $where .= " AND fuel_type IN(". implode(',' , $_POST['fuel_type']) .");
}

$poisks = DB::select("select * from items where (что-то, что всегда будет проверяться) ". $where );

F
FanatPHP, 2020-12-28
@FanatPHP

https://phpdelusions.net/pdo_examples/dynamical_where
Only the body is not called Hatchback, but Hatchback.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question