database - How to setup PHP loop to fetch products and create specs table
I have two tables in a database. Attached images for the same.
The "Name" row in both tables are the same. Table1 consists of the specification details of each item. Table2 is just the list of product names that should be included on the whole page. I want to fetch all the specifications for each product name. For example, the Product Rajwadi dinner set should get all its specifications from Table1. I need to add about 50 such products. The way I want it displayed is also shown in the image below.
The code I have been trying goes like this :
<?php
include("connection.php");
$db_dinner_set = "dinner_set";
$db_names = "names";
$query2= "SELECT * FROM $db_names";
//echo($query);
$statement2 = $connection2->prepare($query2);
$statement2->execute();
$result2 = $statement2->fetchAll();
foreach($result2 as $row){
echo '
'.$row['Name'].'
<br>
<br>
';
$Name = $row['Name'];
$query3= "SELECT * FROM $db_dinner_set WHERE Name = $Name ";
//echo ($query3);
$statement3 = $connection2->prepare($query3);
$statement3->execute();
$result3 = $statement3->fetchAll();
foreach($result3 as $row)
{
echo '
<div class="poem-genre">
'.$row['Items'].'
</div>
';
}
}
?>
Answer
Solution:
Your table design needs a bit of work, but you can still accomplish the task. Join the tables on the name (not ideal):
SELECT d.Name, d.Items, d.pieces, d.image FROM dinner_set d LEFT JOIN names n ON d.Name = n.Name
Then loop through the results in PHP to build an object for each item.
$items = [];
foreach($result3 as $row){
// Add item by name
if (!array_key_exists($row['name'], $items)) {
$items[$row['name']] = [];
}
$piece = [];
// Add attributes of the particular piece
$piece['name'] = $row[Items];
$piece['qty'] = $row[pieces];
// Assign this piece to this item
$items[$row['name']][] = $piece;
}
Now you have an array of items, each item will contain a list of the pieces for that item.
Source