user3653474
user3653474

Reputation: 3852

How to use two tables data in a view in Codeigniter

I have two tables, first table is about topic name and second table shows sub-topics. I want to show from first table topic name then search their corresponding sub-topic and show it in view and so on till topic names are found in first table. But the problem is i can only get one table data in view i.e. main topic table. I have no idea how to get full data of both table and use it.

Database Structure:

enter image description here

Model:

<?php 

    class Topics_Model extends CI_Model {

    function __construct()
        {
              parent::__construct();
        }

    function get_all_topics()
    {
       $this->load->database();
       $this->db->select("*");
       $this->db->from("topics");
       $query=$this->db->get();
       return $query->result();
    }
    }

?>

Controller :

<?php

class drag_drop_course_material extends CI_Controller {

  function drag_drop_course_material()
   {
     parent::__construct();
   }

   function index()
    {
     $this->load->model('topics_model');
     $data['query']=$this->topics_model->get_all_topics();
     $this->load->helper('url');
     $this->load->view('drag_drop_course_material', $data);
    }
}

?>

View:

 <?php
    foreach ($query as $row) {
 ?>
   <li>  $row->topic_name   </li>
 <? }  ?>

Required Output:

enter image description here

Upvotes: 3

Views: 3390

Answers (2)

David Coder
David Coder

Reputation: 1138

Your controller is perfect, your model is perfect just change your view:

In view:

        foreach ($query as $row) 
        { ?>
        <ul>
            <li><?php echo $row['topic_name'];?>
            <ul>
            <?php $this->db->where('sub_topic_id',$row['id'])
            $r = $this->db->get('subtopics');
            if($r->num_rows()>0)
            {
                foreach ($r -> result_array() as $row) {
                $data1[] = $row;
                }
            }
            foreach($data1 as $sub){?>
            //print <li><?php echo $sub['subtopic_name']?></li>
            <? }?>
          </ul>
        </li>
       <? }?>
      </ul>

Upvotes: 0

sandeepsure
sandeepsure

Reputation: 1125

Try this query. We do left join of both tables.

$CI->db->select('*');
$CI->db->from('topic');
$CI->db->join('sub-topics', 'topic.id = sub-topics.sub_topic_id', 'left');
$query = $CI->db->get();
$result =  $query->result(); 

You will get result in your model. return this result from model and access it in controller. Once you print return result in controller you will get idea that how to render it because you already did it above.

Upvotes: 1

Related Questions