There is a large list of lines on the site with 8 different columns, i.e.

<tr> <td>data1</td> <td>data2</td> <td>data3</td> <td>data4</td> <td>data5</td> <td>data6</td> <td>data7</td> <td>data8</td> </tr> 

I need to select only certain strings from the database, I know how to accept and process a post request, if at a post request the field values ​​are all specified, but how can I accept and process a post request if the fields can always be different? For example:

When searching on a site, 8 parameters are specified, according to which there can be a selection and, accordingly, those fields that are empty (that is, no values ​​are specified) should be ignored during a SELECT query. All that comes to my mind is to create a set of conditions (otherwise there is no knowledge)

Please tell me how to form a query to the database (SELECT) with the presence of only those fields for which the data came from the post query.

  • When all the values ​​come in, how does the query look at least? Does this come the names of the fields or faq? - Alexey Shimansky
  • @ Alexey Shimansky, now I will try to formulate ... I have a sample by users, i.e. if I specify the user's country, then only the country is sampled, and if I specify the country and the region, there are already two samples by two parameters, but there are 8 different parameters and each request can have different parameters. The handler comes with the names of fields and their values, but the names of the fields and values ​​come all available only if I select only one value, for example the country, the other fields will come empty but they also need to be processed. Otherwise, I don’t know how to explain - Cinema Trailers

1 answer 1

In general, it will be something like this:

 $sql = 'SELECT `something` FROM `table` WHERE '; $i = 0; foreach($_POST as $key => $val) { if (!empty($val)) { if ($i != 0) $sql .= ' AND '; $sql .= '`'.$key'` = "'.$val.'"'; $i++; } } 

That is, we pass the post array, if the value is not empty, then we add a condition. And besides, if this is not the first pass, we add AND .... Well, or OR or whatever you need.


Although, in fact, at the beginning it is better to filter out empty values ​​through a filter, such as:

 $test = ['test1' => 111, 'test2' => '', 'test3' => '', 'test4' => 'sdfsdf']; $postVars = array_filter($test, function($el){ return !empty($el); }); 

where $test is $_POST , i.e. the data that came with the POST request.

And then just do a loop for the query, as written above.

And of course that query looks very simple, in the sense of being subject to SQL injections, so you should do it, but on the basis of prepared expressions. I hope you know what it is and you can substitute the values ​​yourself.