I'm trying to build a dynamic menu with submenus that inserts links coming from the database. I wrote the code below directly in my view to test and it worked perfectly:
<?php
$this->db->from('categories');
$this->db->where('category_id_parent', 0);
$menu_list = $this->db->get();
foreach ($menu_list->result() as $menu): ?>
<li>
<a href=""><?php echo ucwords($menu->category_title) ?></a>
<?php
$cat_id = $menu->category_id;
$this->db->from('categories');
$this->db->where('category_id_parent', $cat_id);
$submenu_list = $this->db->get();
?>
<ul>
<?php foreach ($submenu_list->result() as $submenu): ?>
<li>
<a href=""><?php echo ucwords($submenu->category_title) ?></a>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
So I decided to create the model and the controller and adapt the new view.
The model looks like this:
public function get_menu() {
$query = $this->db->get_where('categories', array('category_id_parent' => 0));
if ($query->num_rows() > 0):
return $query;
endif;
}
public function get_submenu() {
$query = $this->db->get_where('categories', array('category_id_parent' => 0));
foreach ($query->result() as $row):
$cat_id = $row->category_id;
endforeach;
if ($cat_id != FALSE):
$this->db->from('categories');
$this->db->where('category_id_parent', $cat_id);
$query = $this->db->get();
return $query;
else:
return FALSE;
endif;
}
The controller:
public function menu() {
$data['menu_list'] = $this->Menu_model->get_menu();
$data['submenu_list'] = $this->Menu_model->get_submenu();
$this->load->view('frontend/header', $data);
}
A view:
<?php foreach ($menu_list->result() as $menu): ?>
<li>
<a href="#" ><?php echo ucwords($menu->category_title) ?> </a>
<ul>
<?php foreach ($submenu_list->result() as $submenu): ?>
<li>
<a href="#"><?php echo ucwords($submenu->category_title) ?></a>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
Almost everything works except submenus that repeat the same links.
Where am I going wrong?
I have refactored the get_submenu method just to get the submenu ids:
public function get_submenu() {
$query = $this->db->get_where('categories', array('category_id_parent !=' => 0));
if ($query->num_rows() > 0):
return $query;
endif;
}