Reputation: 67
I have an issue in getting products on parent-category page. My database table structure:
Parent-category:
id -catname
1 - Mobiles & Tablets
2 - Compuetrs
Sub-category:
id cid sub_name
1 1 Mobiles
2 1 Tablets
3 2 Desktops
4 2 Laptops
Products tables structure: My products tables are multiple and based on sub-categories. Example: Tablets products are found under tablets table and mobiles products are found under mobiles table. Products are stored under different tables based on their sub-categories.
id cid sub_id product_name
1 1 1 Lenovo latest mobile
2 2 3 Dell Monitor
Now i want to fetch products from tables(mobiles,tablets,desktops,laptops) on parent category pages. i tried this with union all but at a time only one table is fetching in query. Could anyone suggest something. Thanks in advance.
<?php
if(isset($_GET)) {
$cid = $_GET['id'];
if($cid == 1){
$tablename = "mobiles";
}
if($cid == 2){
$tablename = "computers";
}
$results=mysql_query("SELECT * FROM $tablename WHERE cid = '$cid'");
while($rows=mysql_fetch_array($results)){
// code
}
}
Upvotes: 1
Views: 2176
Reputation: 3743
Query in loop reduces performance, you can always join tables and get data by querying database only once,
Try,
SELECT products.product_name, parent_category.catname
FROM products
JOIN parent_category ON products.cid = parent_category.id
Joins also work on multiple tables, suppose you want to get category as well as sub category,
Try,
SELECT products.product_name, parent_category.catname, sub_category.sub_name
FROM products
JOIN parent_category ON products.cid = parent_category.id
JOIN sub_category ON products.sub_id = sub_category.id
More about joins: here
Upvotes: 3