Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 612
user3653474 Avatar asked Feb 08 '26 03:02

user3653474


1 Answers

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.

like image 130
sandeepsure Avatar answered Feb 12 '26 05:02

sandeepsure



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!