Codeigniter: Cant download database in my library.

When I try to call

$this->load->database(); 

produces the following error: "Call to the database of member functions () for a non-object"
Database autoload doesn't help either ... when I try to autoload it.
all calls to the database for example

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

he says the get method is undefined ...
I have no idea what and where to start ..
\ anyone?

+4
source share
4 answers

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

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

Make sure the connection settings are in order application/config/database.php

What is it like in the library

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

Usage extends CI_Model if try extends Model does not work

 class User_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } } 
+1
source

You can load the database in two ways:

Method 1: Auto Connect

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

Method 2. Manual Connection

$ this-> Download> database ();

Hope the above methods clear your confusion ....

0
source

You make a very common mistake. When you call $this->load->database(); from controller or model , this works because controllers and models are children of CI_Controller and CI_Model respectively. But when you call them from a library that is not a child of any CI base class, you cannot load database () or anything else using the $this-> key. you should use the help &get_instance(); to load the codeigniter instance and use this instance instead of $this . Which suggests the 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 leave a field variable for storing the link to $INST , since you may need to access it in various functions.

The following code would be more appropriate:

  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(); } } 
0
source

All Articles