David Dacruz
David Dacruz

Reputation: 169

How to get all categories of a product in PHP/SQL

I have an sql request that retrieves all the products in the database with it's categories using mysqli_fetch_all, problem arises when a product has two categories I have twice the product coming back in the result or n times as many categories the product has and I cain't get it to output properly in the html template if someone explained to me in php or sql how to do what i wish thanks.

products
--------
id
name
etc ...

categories
----------
id
name

category_product
----------------
category_id
product_id

$sql = "SELECT
          p.id, 
          p.name, 
          p.price, 
          categories.name as category_name 
          FROM products as p 
             JOIN category_product 
                ON p.id = category_product.product_id
             JOIN categories 
                ON category_product.category_id = categories.id";

output => [0] => Array ( 
                   [id] => 3 
                   [name] => product 3 
                   [price] => 1.00 
                   [category_name] => cat 4 ) 
          [1] => Array ( 
                   [id] => 3 
                   [name] => product 3 
                   [price] => 1.00 
                   [category_name] => cat 3 ) 

expected => [0] => Array ( 
                   [id] => 3 
                   [name] => product 3 
                   [price] => 1.00 
                   [category_name] => Array(
                                        [0] => cat 3
                                        [1] => cat 4 ]))

Upvotes: 0

Views: 268

Answers (1)

Nick
Nick

Reputation: 147146

Change your query to generate a GROUP_CONCAT of category names, then after fetching you can split that value using explode in PHP. For example (assuming you are using MySQLi with a connection $conn):

$sql = "SELECT
          p.id, 
          p.name, 
          p.price, 
          GROUP_CONCAT(categories.name SEPARATOR '|') as category_name 
          FROM products as p 
          JOIN category_product ON p.id = category_product.product_id
          JOIN categories ON category_product.category_id = categories.id
          GROUP BY p.id, p.name, p.price";
$result = $conn->query($sql) or die($conn->error);
while ($row = $result->fetch_assoc()) {
    // split the category names into an array
    $row['category_name'] = explode('|', $row['category_name']);
    // do something with the row value
}

Note that you need to specify a separator to GROUP_CONCAT (in this case I've used |) which will not occur in a category name.

Upvotes: 2

Related Questions