4

当我尝试打电话时

$this->load->database();

产生以下错误“调用非对象上的成员函数数据库()”
自动加载数据库也无济于事......
当我尝试自动加载它时。
所有对数据库的调用

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

它说 get 方法未定义...
我不知道从什么开始以及从哪里开始..
\ 有人吗?

4

4 回答 4

12

转到 autoload.phpapplication/config/autoload.php并添加这个

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

确保您的连接设置在 application/config/database.php

比在图书馆这样做

Class MyLib
{
    function getPeople(){
        $CI =   &get_instance();
        $query  =   $CI->db->get('people');
        return $query->result();
    }
}
于 2013-04-09T11:02:14.373 回答
1

如果不工作,请使用扩展 CI_Model 尝试扩展模型

class User_model extends CI_Model { 

     public function __construct() 
     {
           parent::__construct(); 
           $this->load->database();
     }
}
于 2013-04-09T11:22:11.067 回答
0

您可以通过两种方法加载数据库:

方法一:自动连接

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

方法二:手动连接

$this->加载>数据库();

i hope above methods clear your confusion....

于 2016-11-24T11:57:35.063 回答
0

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();
     }
 }
于 2019-10-11T21:25:04.520 回答