[英]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.
我尝试使用union,但是一次只有一个表在查询中获取。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.