I have two tables. Each product could have one or more files. But each file must belong to one product.
**PRODUCTS**
ID PRODUCT_CODE DESCRIPTION
1 a1 small
2 a2 big
**PRODUCT_FILES**
ID PRODUCT_ID FILE_PATH FILE_NAME
1 1 x.pdf x
2 1 y.pdf y
3 2 z.pdf z
I want to have a table which includes
PRODUCT_ID, PRODUCT_CODE, DESCRIPTION, FILE_NAME(s), FILE PATH(s)
My query was;
$query = $this->db->query
("
SELECT products.*,product_files.file_name
FROM products
INNER JOIN product_files
ON products.id = product_files.product_id
GROUP BY products.id
");
$i = 0;
while($row = $query->fetch_assoc())
{
$details[] = array
(
'code' => $row['code'],
'description' => $row['description'],
'file_name' => $row['file_name'],
'file_path' => $row['file_path']
);
}
return $details;
And my php was;
<?php foreach($details AS $product) { ?>
<tr>
<td><?php echo $product['code']; ?></td>
<td><?php echo $product['description']; ?></td>
<td><a href="files/<?php echo $product['file_path']; ?>">
<?php echo $product['file_name']; ?></a></td>
</tr>
<?php } ?>
But with this query and php, product row is duplicating which product has more than one file like;
a1 small x x.pdf
a1 small y y.pdf
a2 big z z.pdf
And than i tried another query with same php code;
$query = $this->db->query
("
SELECT products.*,
GROUP_CONCAT(DISTINCT product_files.file_name SEPARATOR ',')
AS file_name,product_files.file_path
FROM products
INNER JOIN product_files
ON products.id = product_files.product_id
GROUP BY product.id
");
And the result is;
a1 small x,y x.pdf,y.pdf (linked with x.pdf's path)
a2 big z z.pdf
Do i have to explode product_files cell now? If yes, please try to explain with a piece of code?
looks like you’re nearly there!
you just need to do a
GROUP_CONCATon the file_path as well;and, for safety, order the GROUP_CONCAT-ed file_name & file_path, so they’re in the corresponding order.
than you can explode file_name or file_path and loop through each array – to grab the file-path pairs (they’ll be in the same position in each array).