March 5, 2012

Return category and forums in query?

Question by Leeloo

I’m currently developing a simple forum inside CodeIgniter to get a handle on PHP, and I’ve ran into a problem, albeit elementary.

My forum index is made up of categories, which each have a few forums assigned to them. I would like to display the title of each category, and then return each of the forums underneath.

Here is my MODEL at the moment to return the data:

function get_top_level_forums()

{

    $this->db->select('id, title');
    $this->db->from('forum_category');
    $query = $this->db->get();

    if ($query->num_rows() > 0)

    {

        $categories = $query->result();

        foreach($categories as $category)

        {

            $this->db->select('id, title, description');
            $this->db->from('forum');
            $this->db->where('parent_id', 0);
            $this->db->where('category_id', $category->id);
            $query = $this->db->get();

            $forums = $query->result();

        }

        return $categories;

    }

}

I’m struggling to work out how to return all of the data in a single array. I know this is a rookie question, but I’ve poked at it for an hour and can’t see any light at the end of the tunnel!

I know how to use the data in my CONTROLLER and VIEW. I’m just stuck on the MODEL part.

Thanks.

🙂

Answer by Starx

Instead of using a variable to store the result, use an array instead

$forums[] = $query->result();

Full Example:

$forums = array();
foreach($categories as $category)

        {

            $this->db->select('id, title, description');
            $this->db->from('forum');
            $this->db->where('parent_id', 0);
            $this->db->where('category_id', $category->id);
            $query = $this->db->get();

            $forums[] = $query->result();

        }
        //$forums now contains all the query results

Update

To access the variables you can use

$forums[$forumindex][0] -> id;

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!