1
I’m trying to build a dynamic menu with submenus that insert links 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 controller and adapt the new view.
The model was 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);
}
The 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 is working except the submenus that repeat the same links.
Where I’m going wrong?
I redid 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;
}
Welcome to Stackoverflow in English. In order to make your answer more complete the code should be accompanied with a short explanation.
– ramaral
Added. Thank you!
– rbm0407