How do I SELECT them from the database to show all products (table1) under parent_id from the categories (table2)?
For example, I want to show/list all the products under parent_id = 1 (Kid's Clothing) including all products under sub-categories per page using a link like cat.php?id=1
Parent Category ID #1
- Product#1 > category_id #5
- Product#2 > category_id #10
- Product#3 >> category_id #16
- Product#4 >> category_id #20
Parent Category ID #2
- Product#5 > category_id #31
- Product#6 > category_id #33
Parent Category ID #3
- Product#7 > category_id #27
- Product#8 > category_id #29
Here's what I have so far, but it's still not showing all the products in the parent category sqlfiddle
SELECT * FROM products
LEFT JOIN categories
ON products.category = categories.category_id
GROUP BY (SELECT parent_id
FROM categories
WHERE parent_id = 1
GROUP BY parent_id)
DB: categories
CREATE TABLE IF NOT EXISTS `categories` (
`category_id` int(10) NOT NULL AUTO_INCREMENT,
`parent_id` int(10) DEFAULT NULL,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
DB: products
CREATE TABLE IF NOT EXISTS `products` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`product` varchar(255) DEFAULT NULL,
`description` longtext DEFAULT NULL,
`category` int(10) DEFAULT NULL,
`color` varchar(255) DEFAULT NULL,
`sizes` varchar(255) DEFAULT NULL,
`style` varchar(255) DEFAULT NULL,
`material` varchar(255) DEFAULT NULL,
`stock` varchar(255) DEFAULT NULL,
`ws_price` decimal(6,2) DEFAULT NULL,
`rt_price` decimal(6,2) DEFAULT NULL,
`sp_code` varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Structure for CATEGORIES
- Kid's Clothing
- --Big Boys & Girls Apparel
- -------Tops & Tees
- -------Skirt & Pants
- --Baby Boys & Girls
- -------Rompers/Onesies
- -------Baby Accessories
- -------Baby Care & Toys
- --Clothing Set --------Unisex
Code for viewing the products (example):
$getid = $_GET['id'];
$q = mysqli_query($con,"
SELECT products.*, categories.*
FROM products, categories
WHERE products.category = categories.category_id
GROUP BY categories.parent_id= $getid
");
while($row = mysqli_fetch_array($q, MYSQLI_ASSOC)){
$id = $row['id'];
$product = $row['product'];
$cat = $row['category'];
$c = mysqli_query($con,"SELECT title FROM categories WHERE category_id = $cat");
while($r = mysqli_fetch_array($c)){
$pcat= $r['title']; }
echo '<p>ID#'.$id.'-'.$product.' (Category#'.$cat.'-'.$pcat.')</p>';
}
mysqli_close($con);