I have a table called sales
and it has below columns:
'id'
'product_type'
'soldDate'
'text'
'product_type'
examples are: Tshirt-XL
, Tshirt-L
, Tshirt-M
, Trousers-XL
, Trousers-L
, Trousers-M
etc.
I have an array called products
which is;
$products = array('Tshirt','Trausers');
My output is after executing below code:
Tshirt
Tshirt-L
- lorem impsum dolat
Tshirt-XL
- lorem impsum.
- another text. ball.
Trousers
- Trousers-M
text for this one.
And the code itself:
$products = array('Tshirt','Trousers');
foreach ($products as $product) {
echo "<b>";
echo $product;
echo "</b><br>";
$q = "
SELECT *,
SUBSTRING_INDEX(product_type, '-', 1) AS product_typeMain
FROM sales
WHERE SUBSTRING_INDEX(product_type, '-', 1) = '".$product."'";
$statement = $db->prepare($q);
$results = $statement->execute();
$results = $statement->fetchAll();
$unique_product_types = array();
foreach($results as $filter_result){
if ( in_array($filter_result->product_type, $unique_product_types) ) {
continue;
}
$unique_product_types[] = $filter_result->product_type;
echo $filter_result->product_type;
echo "<br>";
$q = "
SELECT *
FROM sales
WHERE product_type = '".$filter_result->product_type."'
";
$statement = $db->prepare($q);
$results = $statement->execute();
$results = $statement->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $value) {
echo "<li>".$value->text."</li>";
}
}
}
I know there are so many foreach loops, so many queries. Also I have worries about performance (more than 100.000 rows, and more than 100 product_type.) Plus I will need to add another query in last foreach loop to make searches (multiple, not one).
I am looking forward to hear best practices to improve. Thanks in advance.