PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
create table products ( id int auto_increment primary key, name varchar(255) ); insert into products (name) values ('Some 8 AMD cores norebook'); create table properties ( id int auto_increment primary key, property varchar(255), category_id int, filter int, index (category_id) ); insert into properties (id, property, category_id, filter) values (1, 'Type', 1, 0), (86, 'CPU cores', 1, 0), (87, 'CPU', 1, 0); create table property_values ( id int auto_increment primary key, property_id int, product_id int, value varchar(64), index (property_id), index (product_id), foreign key (product_id) references products(id) ); insert into property_values (property_id, product_id, value) values (1, 1, 'Notebook'), (86, 1, '8'), (87, 1, 'AMD'); select * from products p join property_values pv on p.id = pv.product_id;
Copy Clear
Copy Format Clear
<?php $request = [ 87=>'AMD', 86=>'8' ]; $filter = implode(' or ', array_fill(0, count($request), '(pv.property_id = ? and pv.value = ?)')); $filter_values = []; foreach($request as $key=>$val) { $filter_values[] = $key; $filter_values[] = $val; } $query = 'select p.* from products p join property_values pv on p.id = pv.product_id where ' . $filter . ' group by p.id, p.name having count(distinct pv.id) = ' . count($request); echo $query . PHP_EOL; $stmt = $pdo->prepare($query); $stmt->execute($filter_values); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); print_r($rows);
Show:  
Copy Clear