Sergio Sergio - 2 months ago 5
MySQL Question

PHP retrieving data from a database

I am having a bit of an issue retrieving and formatting the retrieved info in a way that I intend it to.

Basically I have products IDs that match categories IDs. A product can have multiple categories, and I get the results as expected. But I am trying to format it in a way that for every Product I get a list of Category IDs. Right now I get multiple Product IDs for every Category ID, as such:

Product Id: 65 ––> Categories Id:250
Product Id: 65 ––> Categories Id:249
Product Id: 66 ––> Categories Id:250
Product Id: 66 ––> Categories Id:249
Product Id: 66 ––> Categories Id:252
Product Id: 66 ––> Categories Id:251
Product Id: 66 ––> Categories Id:276
Product Id: 66 ––> Categories Id:268
Product Id: 66 ––> Categories Id:255


I need it to be more like:

Product Id: 65 ––> Categories Id:250, 249
Product Id: 66 ––> Categories Id:250, 249, 252, 251, 276,268, 255


Here is the code I have doing the query:

$sql = "SELECT * FROM `products_categories` ORDER BY `products_categories`.`productid` ASC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Product Id: " . $row["productid"] . " ––> " . "Categories Id:" . $row["categoryid"] . "<br>";
}
} else {
echo "0 results";
}


Thank you in advance for any input.

Answer

USE GROUP_CONCAT

SELECT productid, GROUP_CONCAT(categoryid) as categoryid
FROM products_categories
group by productid
order by productid
Comments