如何在codeigniter 3x的帮助文件中连接数据库?

问题描述 投票:0回答:1

我已经使用CI3x创建了一个新项目,并在HMVC中将其转换为现在,我已经创建了一个helper文件和autoload相同。数据库库也将自动加载。

有一种功能,我试图在数据库中插入一些值,但显示数据库错误有关详细信息,请查看下面的代码和错误

**helper code**
if (!function_exists('create_meta')) {
    function create_meta($data = array()) {
        $CI = &get_instance(); //$CI = & get_instance();
        $CI->load->database();
        if (is_array($data) && !empty($data) && array_key_exists('page_url', $data)) {
            $CI->db->insert("table_name", $data);
        }
    }
}

**Error 1**
A PHP Error was encountered
Severity: Notice

Message: Trying to get property 'load' of non-object

Filename: helpers/Utils_helper.php

Line Number: 518

Backtrace:

File: E:\wamp64\www\dda\apps\helpers\Utils_helper.php
Line: 518
Function: _error_handler

File: E:\wamp64\www\dda\apps\modules\admin\controllers\Category.php
Line: 161
Function: create_meta

File: E:\wamp64\www\dda\index.php
Line: 320
Function: require_once

**Error 2**

Type: Error

Message: Call to a member function database() on null

Filename: E:\wamp64\www\dda\apps\helpers\Utils_helper.php

Line Number: 518

Backtrace:

File: E:\wamp64\www\dda\apps\modules\admin\controllers\Category.php
Line: 161
Function: create_meta

File: E:\wamp64\www\dda\index.php
Line: 320
Function: require_once

请仔细调查,并让我知道您是否有人遇到并解决过同类问题。

预先感谢

php codeigniter codeigniter-3
1个回答
0
投票

从功能中删除$CI->load->database();行,如果您已经在application/config/autoload.php中加载了数据库库。

如果您没有自动加载数据库,请在函数中修改此行:

$CI->load->database();

收件人:

 $CI->load->library('database');

如果您不知道如何自动加载数据库库。打开application / config / autoload.php文件,$autoload['libraries']并添加您的库,如下所示:

$autoload['libraries'] = array('database');
© www.soinside.com 2019 - 2024. All rights reserved.