I have three tables: products (id, name), categories (id, name) and products_categories (product_id, category_id).
Each product belongs to one or more categories.
I want to retrieve all products, and show which ones are already in category "X". My divs are like this:
<span>Category "X"</span>
[some php / fetch_assoc() / … ]
<div class="product">Product A</div>
<div class="product selected">Product B</div>
<div class="product">Product B</div>
For now, it work with two queries: one to fetch all the products, and one to check if the product is in products_categories. So it's a lot of small queries with php inside the first one.
$getAllProducts = "SELECT products.name as productName, products.id as productID FROM products";
$resultProduct=$mysqli->query($getAllProducts);
while($product=$resultProduct->fetch_assoc()){
$reqChecked = "SELECT * FROM products_categories
WHERE product_id=" . $product["productID"] ."
AND category_id=" . $category["id"]; //$category["id"] is given
$resultChecked = $mysqli->query($reqChecked);
$row = $resultChecked->fetch_row();
$selected = ""
if ( isset($row[0]) ) {
$selected = "selected";
}
It is possible to do it with only one query? I tried with a left join (products_categories on products), but the products belonging to multiple categories are listed for every categories they're in.
EDIT
Here is some sample data
Product table
+----+-----------+
| id | name |
+----+-----------+
| 1 | product_1 |
| 2 | product_2 |
| 3 | product_3 |
+----+-----------+
category table
+----+------------+
| id | name |
+----+------------+
| 1 | category_1 |
| 2 | category_2 |
| 3 | category_3 |
+----+------------+
joining table
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1 | 1 |
| 1 | 2 |
| 2 | 2 |
+------------+-------------+
Now, let's say I'm on a page editing category_2, and I want the following result:
+------------+--------------+-------------+
| product_id | product_name | category_id |
+------------+--------------+-------------+
| 1 | product_1 | 2 | --product_1 belongs to category_1 and category_2, but I only need it one time.
| 2 | product_2 | 2 |
| 3 | product_3 | NULL | --product_3 belongs to nothing but I want to see it.
+------------+--------------+-------------+