Category.php - products show in subcats but not in categories if it has no subcategories
Below is my category.php that uses a switch statement to either show subcategories or products. When i click on a subcategory, it displays the products like it's supposed to. However, if the category has NO SUBCATEGORIES, no products will show at all.
Is this a case where the switch statement needs to be altered, the entire foreach loop needs to be in an if statement or is there something wrong with the db and the ids... all of my cats in the menu have a parent_id = 0, subcats correspond to the id for the category table, the products are assigned a category_id. Is this a JOIN thing开发者_StackOverflow?
<?php
foreach ($listing as $key => $list){
echo "<img src='".$list['thumbnail']."' border='0' align='left' />";
echo "<h4>";
switch($level){
case "1":
echo anchor('welcome/cat/'.$list['id'],$list['name']);
break;
case "2":
echo anchor('welcome/product/'.$list['id'],$list['name']);
break;
}
echo "</h4>";
echo "<p>".$list['shortdesc']."</p><br style='clear:both'/>";
}
?>
Any help is much appreciated.
the $level is located in the welcome controller.
function cat($id){
$cat = $this->MCats->getCategory($id);
if (!count($cat)){
redirect('welcome/index','refresh');
}
$data['title'] = "Company |" .$cat['name'];
if ($cat['parentid'] < 1){
// show other cats
$data['listing'] = $this->MCats->getSubCategories($id);
$data['level'] = 1;
}else{
// show products
$data['level'] = 2;
$data['listing'] = $this->MCats->getProductsByCategory($id);
}
$data['category'] = $cat;
$data['main'] = 'category';
$data['navlist'] = $this->MCats->getCategoriesNav();
$this->load->vars($data);
$this->load->view('template');
}
get products by category function... This selects the products based on category_id in the products table. still no show though...
function getProductsByCategory($catid){
$data = array();
$this->db->select('id,name,shortdesc,thumbnail');
$this->db->where('category_id',$catid);
$this->db->where('status','active');
$Q = $this->db->get('products');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
Try doing following. First you check in database, does requested category have products. Then check does it have subcategories. If sencond is false, then choose first and display products linked to main category.
If main category has no products, but it does have subcategories and the do have products, then it work as described in your code.
If main category has no products and no subcategories, then there is no point in displaying it at all.
Count the number of sub categotries returned in your model; if it's 0; return false
to the controller. Then do a test to see if $listing
is an array, or false, and output the appropiate data or message to the user.
精彩评论