K Cloud K Cloud - 4 months ago 109
PHP Question

How to call database function into custom library in Codeigniter?

I have created a library and am trying to access the database through it in codeigniter.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class History {

function __construct() {
//$CI->load->database();
//$this->load->library('database');
$CI =& get_instance();
$CI->load->database();
}

public function create_history($id){
//$this->load->database();
$sql = "INSERT INTO inventory_history SELECT null,i.* FROM inventory i where i.inventory_id = :id";
$query = $this->CI->db->conn_id->prepare($sql);
$query->bindParam(':id', $id, PDO::PARAM_INT);
return $query->execute();
}}


But I am getting error near the insert query. Going through Google I went around someone telling to use
$this->ci->db
to execute query. I'm not able to point out why there is error in database execution. How can I call database function into my custom library in codeigniter?

Answer

is it this?

class YourLibName {
   private $CI;

   function __construct() {
       $this->CI =& get_instance();
       $this->CI->load->database();
   }

}

Update: I think you should not load and use database object in library. You better create a model and call it. A library should be independent and can be used with other application.