Search code examples
phpdatabasecodeignitermodel-view-controller

How to access the database from a CodeIgniter library file?


I am trying to build a custom library of a Shopping Cart. I had some issues with loading the database library into the Cart class but I solved that with using:

$CI =$ get_instance();
$CI->load->database();

But now whenever I want to use the database library it gives me the error: "Trying to get property of non-object" on this line:

$this->CI->db->insert("carts", $data);

I should mention that I declared the $CI variable at the top of my class like this:

var $CI;

Solution

  • If $CI is a class variable, as you say it is, then you'll need to use

    $this->CI =& get_instance();
    $this->CI->load->database();
    

    instead of

    $CI =& get_instance();
    $CI->load->database();
    

    initialize $this->CI in constructor to make available in every methods.