Chris
Chris

Reputation: 11

PHP SQL - Joining three tables

I have three tables called product, product_category and category with product_category being the linking table.

How can I join these tables using SQL in PHP?

The linking table has only productID linking to the product table and catID linking to the category.

Upvotes: 0

Views: 5594

Answers (2)

Nanne
Nanne

Reputation: 64419

Your query should look something like this: Added the requirement that there should be a productId and categoryId from a variable:

$query = "SELECT * FROM
          product p
            JOIN product_category pc ON p.id = pc.productId
            JOIN category c ON c.id = pc. categoryId
          WHERE p.id = {$productId}
            AND c.id = {$categoryId}";

Upvotes: 2

MatBailie
MatBailie

Reputation: 86765

Something like this?

SELECT
  *
FROM
  product
INNER JOIN
  product_category
    ON product_category.productID = product.productID
INNER JOIN
  category
    ON category.catID = product_category.catID

Upvotes: 4

Related Questions