【问题标题】:Codeigniter 3 Fatal error: Call to a member function database() on nullCodeigniter 3 致命错误:在 null 上调用成员函数 database()
【发布时间】:2016-06-24 15:59:01
【问题描述】:

我认为无法连接到数据库,我不知道为什么。

我查看了 stackoverflow 并发现了以下问题: here 并没有帮助我解决我的问题。

我已阅读 Codeigniter 3 的文档:here 并使用了选项手动连接

我的应用程序控制器中的类如下所示:

class home extends CI_Controller {

    /**
     * Class constructor
     * Load database lib
     */
    public function __construct()
    {
            $this->load->database();

    }

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/home.php/welcome
     *  - or -
     *      http://example.com/home.php/welcome/index
     */
    public function index()
    {
        $query = $this->db->get('users');

        foreach ($query->result() as $row)
        {
            var_dump($row->fullName); //testing purpose
        }

        //$this->load->view('home', $data);

    }

我的应用程序中的数据库配置如下所示:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
    'dsn'      => '',
    'hostname' => 'localhost',
    'username' => 'user',
    'password' => 'password',
    'database' => 'tasks',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt'  => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => FALSE
);

当我访问http://localhost/home.php/welcome

我收到此错误:

致命错误:在 null 上调用成员函数 database() \www\task\application\controllers\home.php 在第 12 行

我试过 var_dump($this->load) ,它是一个空值,从这里我假设它无法建立到数据库的连接。

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    由于您正在扩展 CI_Controller 类并选择重载 __construct 方法,因此您只需调用父构造即可开始利用 CI 的核心功能。

    class home extends CI_Controller
    {
        public function __construct()
        {
            // $this->load does not exist until after you call this
            parent::__construct(); // Construct CI's core so that you can use it
    
            $this->load->database();
        }
    }
    

    更多详情请参阅http://www.codeigniter.com/user_guide/general/controllers.html#class-constructors

    【讨论】:

    • oO,是的,在您的指导下,我现在才发现这个。 **与其直接在控制器中编写数据库操作,不如将查询放在模型中,以便以后轻松重用。 ** 谢谢。
    • @Starlays 不客气。是的,在使用 MVC 架构时,通常应该将查询放入模型中。
    【解决方案2】:

    在我的情况下,接受的解决方案并没有解决问题。

    我解决了:

    $CI =& get_instance();//Put this before call $this->
    

    现在不要调用 $this->,而是使用 $CI->。

    【讨论】:

      【解决方案3】:

      就我而言,我只是添加了

      parent::__construct();
      

      构造函数

      然后像这样连接并关闭

      $this->db=$this->load->database('DB', TRUE);
      //close
      $this->db->close();
      

      【讨论】:

        猜你喜欢
        • 2018-06-22
        • 2020-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-18
        相关资源
        最近更新 更多