$Query = "SELECT * FROM items WHERE brand IN ('" . implode("','", $brand) . "') ". if(!empty($color)){ AND color IN ('" . implode("','", $color) . "') } if(!empty($style)){ AND style IN ('" . implode("','", $style) . "') } ." "; 

$ brand, $ style, $ color - arrays with values, if they are empty then the expression is not executed

  • And why are you duplicating questions? and why do you need to write it in one line? $query="select ... where 1=1"; the next line, separately if( !empty($color) ) $Query.=" AND color IN ..."; - Mike
  • Will you have to use either if (as in @Mike) or construction ()? : type (empty($brand))? "": implode(,)) (empty($brand))? "": implode(,)) - nick_n_a
  • A SQL query does not support if, instead of there case when then else end is used. Correct the question header, otherwise it looks incorrect. - nick_n_a

4 answers 4

 $query = "SELECT * FROM items WHERE brand IN ('" . implode("','", $brand) . "') "; if(!empty($color)){ $query .= "AND color IN ('" . implode("','", $color) . "')"; } if(!empty($style)){ $query .= "AND style IN ('" . implode("','", $style) . "')"; } ." "; $query .= ';'; 
    1. And did not try to remove AND color IN in brackets? And further in the text.
    2. The construction as a whole is strange. This is not a screen output, but a concatenation.
    3. Generating dynamic queries this way is very bad

    code

     $db = mew mysqli(данные для коннекта); $brandWhere = 'brand IN ('.str_pad('',count($brand)*2-1,'?,').')'; $colorWhere = empty($color))?'':' AND color IN ('.str_pad('',count($color)*2-1,'?,').')'; $styleWhere = empty($style))?'':' AND style IN ('.str_pad('',count($style)*2-1,'?,').')'; $bind = str_pad('',count($brand)+count($color)+count(style),'s'); $stmt = $db->prepare("SELECT * FROM items WHERE ".$brandWhere.$colorWhere.$styleWhere;) $params = [$bind]; foreach($brand as &$e) $params[] = &$e; foreach($color as &$e) $params[] = &$e; foreach($style as &$e) $params[] = &$e; call_user_func_array([$stmt,'bind_param'], $params); $stmt->execute(); 
    • very bad - I'm afraid that will not convince anyone. Tell us why, or at least attach a link to the story. - D-side

    If I understand correctly, you need to add sample terms. You have two solutions:

    1) Select data from the database, and then in php (can be any other language) perform a comparison. For example, in php, check that you received data from byzy: is_null () . And then already if, else, elseif or case ... See for yourself what will be more convenient for you to use.

    2) Select data, and compare them in the DBMS . For example: SELECT IF (brand > 'ваше значение', brand, NULL) FROM items;

      Can so

       class DbHelper { public static function attachBatchParams(&$query, &$binds, $placeholder, $values) { $placeholders = array(); foreach ($values as $key => $value) { $parameter = "{$placeholder}_{$key}"; $binds[$parameter] = $value; $placeholders[] = $parameter; } $query = str_replace($placeholder, implode(', ', $placeholders), $query); } } $binds = array(); $query = " SELECT * FROM items WHERE 1 "; if ($brands) { $query .= "AND brand IN (:brands) "; DbHelper::attachBatchParams($query, $binds, ':brands', $brands); } if ($colors) { $query .= "AND color IN (:colors) "; DbHelper::attachBatchParams($query, $binds, ':colors', $colors); } if ($styles) { $query .= "AND style IN (:styles) "; DbHelper::attachBatchParams($query, $binds, ':styles', $styles); } 

      Such code is easier to read, Plus, at the output, get a query with ready placeholders and an array of parameters that need to be attached via bindParam

      PDO http://php.net/manual/en/pdostatement.bindparam.php

      MySQLi http://php.net/manual/en/mysqli-stmt.bind-param.php

      This will make your code more secure.

      - UPDATED -

      I think the author would be able to find it using the links from the documentation I indicated, but added half a page of code for rjhdby

       $db = new \PDO('mysql:host=127.0.0.1;dbname=test', 'root', ''); //Код указанный выше $sth = $db->prepare($query); foreach ($binds as $placeholder => $value) { $sth->bindParam($placeholder, $value); } $sth->execute(); 
      • And how does this code protect against, for example, SQL injection? - rjhdby
      • And how do you think why bindParam function exists at all. Accidentally, not to cut flies off cutlets, when the request is first prepared, and then the data is inserted that cannot modify the request itself? - Ninazu
      • Now, if you now demonstrate where in your code bind_param, then I apologize directly. At first glance, no preparation of the request and data you and does not smell. - rjhdby
      • Placeholders will be contained in the $ binds array, note that the array is passed to the function by reference to the fill. As well as $ query , in which placeholder will be replaced with an array placeholders. You can of course through ? like you, but I like the nominal ones, because when debugging, it is immediately clear where what value will be. Specifically to the function itself, there is no bindParam in the code, since it is not clear what the author uses, and left a mark under the code - Ninazu
      • Do you think that the author of such a question will guess what you had in mind, will reach enlightenment and will magically add another half a page of code for the proper use of your bind ? Here we need a concrete working example (well, maybe with a small revision of the file) "from" and "to", otherwise even the best intentions will not reach the goal. Show how to use your code, and perhaps you will understand and the world will become closer to perfection. - rjhdby