CodeIgniter Forums
Database Query not displaying expected output. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Database Query not displaying expected output. (/thread-11966.html)



Database Query not displaying expected output. - El Forum - 09-30-2008

[eluser]JasonS[/eluser]
I have a category structure which looks like this.

Bike
- New
Cars

Bike is the parent of New.

I am trying to create a query which will generate an array to display the above output.

What I have currently outputs

Bike
- New

But Cars gets lost. Could someone have a peek and tell me where I am going wrong.

Cheers.
Code:
$this->db->where('parent', '0');
        $query = $this->db->get('categories');
        
        $count = 0;
        
        foreach($query->result() as $row)
        {
            $array[$count]['id'] = $row->id;
            $array[$count]['name'] = $row->name;
            
            $this->db->where('parent', $row->id);
            $newquery = $this->db->get('categories');
            if ($newquery->num_rows() > 0)
            {
                foreach($newquery->result() as $newrow)
                {
                    $array[$count]['id'] = $newrow->id;
                    $array[$count]['name'] = '  - ' . $newrow->name;
                }
            }
            
            $count++;
        }



Database Query not displaying expected output. - El Forum - 09-30-2008

[eluser]Sumon[/eluser]
You miss increment the counter $count for inner for loop.

Try to use this one
Code:
foreach($query->result() as $row)
        {
            $array[$count]['id'] = $row->id;
            $array[$count]['name'] = $row->name;
            
            $this->db->where('parent', $row->id);
            $newquery = $this->db->get('categories');
            if ($newquery->num_rows() > 0)
            {
                foreach($newquery->result() as $newrow)
                {
                    $count++;
                    $array[$count]['id'] = $newrow->id;
                    $array[$count]['name'] = '  - ' . $newrow->name;
                }
            }
            
            $count++;
        }