Kevin Florenz Daus
Kevin Florenz Daus

Reputation: 598

Codeigniter : Cant load database in my library.

When I try to call

$this->load->database();

yields the following error `"Call to a member function database() on a non-object"
Autoloading the database doesnt help too...
when I try to autoload it.
all calls to database like

$this->db->get('people');

it says get method is undefined...
I have no clue what and where to start..
\ anyone ?

Upvotes: 4

Views: 19378

Answers (4)

S.Ahsan
S.Ahsan

Reputation: 399

You are doing a very common mistake. When you call $this->load->database(); from controller or model it works because controllers and models are child of CI_Controller and CI_Model respectively. But when you are call them from Library which is not a child class of any basic CIclass you cannot load database() or anything else using $this-> key. you must use the help of &get_instance(); to load codeigniter instance and use that instance instead of $this. Which suggests following Code:

$INST=&get_instance();//Store instance in a variable.
$INST->load->database();//If autoload not used.
$INST->db->get('people');//or Your desired database operation.

It is better to keep a field variable to hold the reference to $INSTas you may need to access it in various functions.

Following Code will be more eligent:

 class MyLib{
     var $INST;
     public function __construct() 
     {
         $INST=&get_instance();//Store instance in a variable.
         $INST->load->database();//If autoload not used.
     }

     function getPeople(){
         $query  =  $INST->db->get('people');
         return $query->result();
     }
 }

Upvotes: 0

sonu sharma
sonu sharma

Reputation: 51

You can load the database by two methods:

Method 1:Automatic Connecting

$autoload['libraries']=array('database');

Method 2: Manual Connecting

$this->load>database();

i hope above methods clear your confusion....

Upvotes: 0

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

Go to autoload.php in application/config/autoload.php and add this

$autoload['libraries'] = array('database'); // add database in array

Make sure your connection settings are fine in application/config/database.php

Than in the library do it like this

Class MyLib
{
    function getPeople(){
        $CI =   &get_instance();
        $query  =   $CI->db->get('people');
        return $query->result();
    }
}

Upvotes: 12

asvignesh
asvignesh

Reputation: 788

Use extends CI_Model if not working try extends Model

class User_model extends CI_Model { 

     public function __construct() 
     {
           parent::__construct(); 
           $this->load->database();
     }
}

Upvotes: 1

Related Questions