Codeigniter:无法在我的库中加载数据库。

Codeigniter:无法在我的库中加载数据库。,codeigniter,codeigniter-2,Codeigniter,Codeigniter 2,当我试着打电话时 $this->load->database(); 产生以下错误`“对非对象调用成员函数database()” 自动加载数据库也没有帮助… 当我尝试自动加载时 所有对数据库的调用,如 $this->db->get('people'); 它说get方法未定义。。。 我不知道该从哪里开始……\ 有人吗?进入application/config/autoload.php中的autoload.php并添加这个 $autoload['libraries'] =

当我试着打电话时

$this->load->database();
产生以下错误`“对非对象调用成员函数database()”
自动加载数据库也没有帮助…
当我尝试自动加载时
所有对数据库的调用,如

$this->db->get('people');
它说get方法未定义。。。
我不知道该从哪里开始……
\
有人吗?

进入
application/config/autoload.php
中的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();
    }
}

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

class User_model extends CI_Model { 

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

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

方法1:自动连接

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

方法2:手动连接

$this->load>database()


我希望以上方法能消除您的困惑……

您犯了一个非常常见的错误。当您调用
$this->load->database()时controller
model
的code>之所以有效,是因为控制器和模型分别是
CI\u controller
CI\u model
的子对象。但当您从不是任何基本
CI
类的子类的库中调用它们时,您不能使用
$this->
键加载database()或任何其他内容。您必须使用
&get_instance()的帮助
加载codeigniter实例并使用该实例而不是
$this
。建议使用以下代码:

$INST=&get_instance();//Store instance in a variable.
$INST->load->database();//If autoload not used.
$INST->db->get('people');//or Your desired database operation.
最好保留一个字段变量来保存对
$INST
的引用,因为您可能需要在各种函数中访问它

下面的代码将更容易识别:

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

:(…仍然不工作…我将代码放入构造中..并添加了变量来设置$CI..仍然不走运…如果自动加载数据库,则不必执行此操作。只需使用
$CI->db->get('people');
即可工作$CI=&get_instance()..yikes看起来此代码会影响其他代码..@Kebyangblablabla我已经编辑了我的答案并对其进行了简化。查看它以解决您的问题。还有,当您有了为什么使用库的模型时,我只需要访问我库中数据库中的一些内容。&get_instance();我认为这是一个输入错误..对不起..我正在将我的代码迁移到模型中..啊..不眠之夜..哀哉哀哉。。。