$filter = NULL;
if(isset($_GET['filter'])){
$_GET['filter'] = sanitize($_GET['filter']);
if(preg_match('#[0-9]#',$_GET['filter'])) $filter = "AND `banner` = '" . $_GET['filter'] . "'";
elseif(strlen($_GET['filter']) == 2) $filter = "AND `country` = '" . $_GET['filter'] . "'";
else {
$arr = array_map(function($v){return str_replace("'", "", $v);}, explode('-', $_GET['filter']));
$names = implode("' , '", $arr);
$filter = "AND `category_id` in (SELECT `category_id` FROM `categories` WHERE `name` IN ('$names'))";
}
}
$_GET['filter'] = '1.5.2'; # AND `banner` = '1.5.2'
$_GET['filter'] = 'RU'; # AND `country` = 'RU'
$_GET['filter'] = 'Тег-Тег'; #AND `category_id` in (SELECT `category_id` FROM `categories` WHERE `name` IN ('Тег' , 'Тег'))
$_GET['filter'] = '1.5.2_RU_Тег-Тег'; # AND `banner` = '1.5.2' AND `country` = 'RU' AND `category_id` in (SELECT `category_id` FROM `categories` WHERE `name` IN ('Тег' , 'Тег'))
$_GET['filter'] = '1.5.2_RU'; # AND `banner` = '1.5.2' AND `country` = 'RU'
$sql = [];
if(isset($_GET['filter'])) {
$filter = sanitize($_GET['filter']);
$filter = explode('_', $filter);
for ($i = 0; $i < count($filter); $i++) {
if (preg_match('#^[0-9|\.]+$#', $filter[$i]))
$sql[] = "AND `banner` = '{$filter[$i]}'";
elseif (preg_match('#^[A-Z]{2}$#', $filter[$i]))
$sql[] = "AND `country` = '{$filter[$i]}'";
else {
$tags = array_map(function($v) {
return str_replace("'", "", $v);
}, explode('-', $filter[$i]));
$names = implode("' , '", $tags);
$sql[] = "AND `category_id` in (SELECT `category_id` FROM `categories` WHERE `name` IN ('{$names}'))";
}
}
}
$sql = implode(' ', $sql);
echo $sql; // это пихать в запрос к БД
$_GET['filter']
, это примеры запросов и их результат $param = filter_input(INPUT_GET, 'filter', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$filters = explode('-', $param);
$banner = $country = NULL;
$tags = [];
if( count($filters)) {
foreach($filters AS $filter) {
if( preg_match('/^[0-9\.]+$/', $filter)) { // 1.5.9
$banner = $filter;
} elseif( preg_match('/^(RU|EN)$/', $filter) { // RU
$country = $filter;
} else { // tag
array_push($tags, $filter);
}
}
}
$conditions = [];
$params = [];
if($banner) {
array_push($conditions, "`banner` = ?");
array_push($params, $banner);
}
if($country) {
array_push($conditions, "`country` = ?");
array_push($params, $country);
}
if(count($tags)) {
foreach($tags AS $tag) array_push($params, $tag);
array_push($conditions, sprintf(
"`category_id` IN (SELECT `category_id` FROM `categories` WHERE `name` IN (%s)",
implode(',', str_split( str_repeat('?', count($tags))))
));
}
$query = 'SELECT * FROM sometable';
if( count($conditions)) $query = $query . ' WHERE ' . implode(' AND ', $conditions);
$stmt = $dbh->prepare($query);
if( $stmt->execute($params)) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}