Thursday, February 16, 2017

How to access database in custom library codeigniter

  1. Create your library, example “sample.php”
  2. defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Sample
    {
     protected $ci;
    
     public function __construct()
     {
            $this->ci =& get_instance();
     }
    
     public function debug($id)
     {
      $table = $this->ci->db->get_where('table', array('id' => $id))->num_rows();
    
      if (empty($table)) {
       $result = 'table is empty';
      } else {
       $result = $table;
      }
    
      return $result;
     }
    
    }
    
  3. Load your library in controller
  4. defined('BASEPATH') OR exit('No direct script access allowed');
    
    class Testing extends READY_Controller {
    
     public $page = 'Training';
    
     public function __construct()
     {
      parent::__construct();
    
      //Load Dependencies
      $this->load->library('sample');
     }
    
     public function index()
     {
      $data['result'] = $this->db->get('table')->result();
    
      $this->load->view('sampleView', $data); 
     }
    
    }
    
  5. So, call function library in your views.
  6. foreach ($result as $row) {
    
    echo $this->sample->debug($row->id) . “\n\n\n”;
    
    }
    

No comments:

Post a Comment