简体   繁体   中英

How do I list all the products in the sub-categories for the top categories

My database category and product are:

Category Table : id,name,parent_id

Product Table : id,name,category_id

My Category menu is:

-Category A
--Category A1
--Category A2
---Category A2a etc..

Each product has only one category related:

Product1 -> Category A1
Product2 -> Category A2
Product3 -> Category A2a etc..

The code of all of the product category and subcategory

category.php?category_id=1 (exp. category A)

<?php
function FetchAllRows($sql) {
  global $db;
  $stmt=$db->prepare($sql);
  $stmt->execute();
  return $stmt->fetchAll();
}

function getCategoryChild($children) {
    $sql = "SELECT * FROM `category` WHERE `parent_id` = $children";
    $rows = FetchAllRows($sql);

    $sub_category_id = array();
    foreach($rows as $row) {
      // $sub_category_id[$row['id']] = getCategoryChild($row['id']);
      $cat = getCategoryChild($row['id']);
      $sub_category_id[] = array(
        'children' => $cat,
        'category_id' => $row['id']
      );
    }

    return $sub_category_id;
}

$a = getCategoryChild($category_id);
echo $in = join(',', array_fill(0, count($a), '?'));

$query="SELECT * FROM product WHERE category_id IN ($in)";

I tried this latest application. We did not get results. My English is not good. Hopefully presence. Until the array elements in I want to transfer into SQL.

I solved the problem.

I delete these two lines.

echo $in = join(',', array_fill(0, count($a), '?'));
$query="SELECT * FROM product WHERE category_id IN ($in)";

I invested only category_id 's.

  foreach($a as $index => $b) { 
    $subs[$index] = $b['category_id'];
  }

  $ids = implode($subs,',');
  $query = $db->query("SELECT * FROM `product` WHERE category_id IN($ids);");

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