Codeigniter 3 致命错误:在 null 上调用成员函数 database()

Sta*_*ays 2 php codeigniter

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

我查看了 stackoverflow 并发现了这个问题: 在这里,它并没有帮助我解决我的问题。

我已经阅读了 Codeigniter 3: here 中的文档并使用了Manually Connecting选项。

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

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

    }
Run Code Online (Sandbox Code Playgroud)

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

$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
);
Run Code Online (Sandbox Code Playgroud)

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

我收到此错误:

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

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

Mon*_*eus 7

由于您正在扩展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();
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅http://www.codeigniter.com/user_guide/general/controllers.html#class-constructors

  • @Starlays 不客气。是的,在使用 MVC 架构时,通常应该将查询放入模型中。 (2认同)