Codeigniter : Cant load database in my library.

非 Y 不嫁゛ 提交于 2019-12-10 15:49:21

问题


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 ?


回答1:


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



回答2:


Use extends CI_Model if not working try extends Model

class User_model extends CI_Model { 

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



回答3:


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....




回答4:


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


来源:https://stackoverflow.com/questions/15900120/codeigniter-cant-load-database-in-my-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!