简体   繁体   中英

Display products of sub-categories on parent category page in php, mysql

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 
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM