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();
$query="select ... where 1=1";the next line, separatelyif( !empty($color) ) $Query.=" AND color IN ...";- Mike(empty($brand))? "": implode(,))(empty($brand))? "": implode(,))- nick_n_a