我有 category
存储所有 category
的表信息 [ parent
和 child
两者],category_child
存储 parent
的表和 child
category relation
, 和 product_category
存储 child_category
之间关系的表和 product
.
category
- 所有类别 {cid
,cname
,isParent
,status
} 列。category_child
- 现实{parent_id
,child_id
}.category_product
-关系{product_id
,child_category_id
product
- 所有产品详细信息{pid
,pname
,pimage
,pprice
,pstock
我在首页显示所有父类别链接。现在,每当有人单击父类别链接时,我想显示 4 product
每个信息 child category
的 parent category
.
这是我的代码,目前它是可怕的,我正在寻求一些帮助以尽可能地减少它。
$fetchChild = $mysqli->query("SELECT child_id from category_child where parent_id='".$mysqli->real_escape_string($pid)."'");
$listchild = array();
if($fetchChild->num_rows > 0) {
$n = 1;
while($storeChild = $fetchChild->fetch_assoc()) {
$listchild['child_id'][$n] = $mysqli->query("SELECT product_id from category_product where child_category_id='".$mysqli->real_escape_string($storeChild[$n])."'");
if($listchild['child_id'][$n]->num_rows > 0) {
$i = 1;
while($storeMore = $listchild['child_id'][$n]->fetch_assoc()) {
$listchild['product_id'][$i] = $mysqli->query("SELECT pid, pname, pimage, pprice, pstock from product where pid='".$mysqli->real_escape_string($storeMore[$i])."'");
if($listchild['child_id'][$n]['product_id'][$i]->num_rows > 0) {
$me = 1;
while($smeLast = $storeMore[$i]->fetch_assoc()) {
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pid'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pname'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pimage'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pprice'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pstock'];
$me++;
}
} else {
echo '<meta http-equiv="refresh" content="0; url=index.php?error=Something+Went+Wrong+We+are+Fixing+it" />';
}
$listchild['product_id'][$i]->free();
$i++;
}
}
$listchild['child_id'][$n]->free();
$n++;
}
} else {
echo '<meta http-equiv="refresh" content="0; url=index.php" />';
}
$fetchChild->free();
请帮助减少我代码中的嵌套 while 和查询。
谢谢
最佳答案
如果需要,您可以使用 JOIN 将所有内容放入一个 SQL 查询中声明。
SELECT `category`.*, `product`.* FROM `product`
LEFT JOIN `category_product` ON `category_product`.`product_id` = `product`.`pid`
LEFT JOIN `category_child` ON `category_child`.`child_id` = `category_product`.`child_id`
LEFT JOIN `category` ON `category`.`cid` = `category_child`.`child_id`
WHERE `category_child`.`parent_id`='".$mysqli->real_escape_string($pid)."'
但我认为这不是最好的解决方案。
附言。顺便说一句,您的代码中没有每个子类别 4 个产品的 LIMIT,所以我也没有放。
关于php - 通过 PHP 中的父类别从子类别中获取产品详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19124545/