I have a database with two tables with category and product names. I want to display products by category.
how
Category 1 -Product 1 -Product 2 Category 2 -Product 1 -Product 2
But my code returns the category name with each product. how
Category 1 -Product 1 Category 1 -Product 2 Category 2 -Product 1 Category 2 -Product 2
Here is my code attempt:
Model
function NestedProducts() { $sql = "Select C.c_name, P.productname From categories C left join products P on C.id = P.category_id Order by C.c_name"; $query = $this->db->query($sql); return $query->result_array(); }
controller
public function index() { $data['productsbycategory'] = $this->Model->NestedProducts(); $this->load->view('home', $data); }
View
<?php foreach($productsbycategory as $row) : ?> <div> <h4><?php echo $row['c_name']; ?></h4> <div> <h6><?php echo anchor('method/'.$id, $row['productname']); ?></h6> </div> </div> <?php endforeach; ?>
source share