How to do a search in several fields correctly, given that each field has its own values. I do something like this:

$where = ''; $where .= (!empty($s)) ? " WHERE one ='$s' " : ''; $where .= (!empty($s2)) ? " AND two ='$s2' " : ''; $where .= (!empty($s3)) ? " AND three ='$s3' " : ''; $where .= (!empty($s4)) ? " AND four = '$s4' " : ''; $where .= (!empty($s5)) ? " AND five = '$s5' " : ''; $where .= (!empty($s6)) ? " AND six = '$s6' " : ''; $where .= (!empty($s7)) ? " AND seven = '$s7' " : ''; $sql = "SELECT * FROM invoices $where"; 

But in this case, the one field should always be filled. And I need to do a search if at least one value out of 7 is filled.

    2 answers 2

    There are such things - cycles and arrays.

     $conditions = array(); $columns = array('one', 'two', 'three', 'four', 'five', 'six', 'seven'); for ($i = 0; $i < 8; $i++) { if (!empty(${'s' . $i})) { $conditions[] = sprintf("%s = '%s'", $columns[$i], ${'s' . $i}); } } $query = 'SELECT * FROM invoices'; if (sizeof($conditions)) { $query .= ' WHERE ' . implode(' AND ', $conditions); } 

    And if you do not hammer in variables with meaningless names and immediately approach the mind (get data in the format [FieldName => Value]), then the cycle becomes even easier.

     foreach ($data as $field => $value) { if ($value) { $conditions[] = sprintf("%s = '%s'", $field, $value); } } 

      if ($s || $s2 || $s3 || $s4 || $s5 || $s6 || $s7){ // ваш код }