我是codeigniter的新手,我开发了一个代码来对数据库进行查询。我使用$this->load->database();
加载数据库并执行查询,但是当我运行代码时,浏览器会给我以下错误消息:
A PHP Error was encountered Severity: Notice Message: Undefined property: Tutorial::$load.
Fatal error: Call to a member function database() on a non-object
这是我正在使用的代码:
class Tutorial extends CI_Controller {
public function tutorial() {
$this->load->database();
$query = $this->db->query('SELECT user,pass,email FROM tablex');
foreach ($query->result() as $row) {
echo $row->title;
echo $row->name;
}
我确信我的数据库配置文件中的$db
变量已正确设置,我甚至尝试为autoload.php配置文件中的所有页面自动加载数据库;仍然有同样的问题。任何想法如何去做?
答案 0 :(得分:5)
更改
$this->load->database();
到
$this->load->library('database');
数据库不是直接的方法。它是codeigniter中的一个库,您必须将其作为库加载。
您还可以在database
中自动加载autoload.php
库。
<强>更新强>
您的班级和方法使用相同的名称。在PHP4中,与类名同名的方法被视为构造函数,但如果使用的是codeigniter 2+,则必须使用PHP5构造函数
function __construct()
{
parent::__construct();
/*Additional code which you want to run automatically in every function call */
}
您无法在Codeigniter 2+中为类名提供相同的名称。将方法更改为其他任何方法。如果您希望默认加载方法,可以将方法命名为index
。
这可以解决您的问题。
答案 1 :(得分:2)
CodeIgniter用户指南,Creating Libraries部分:
要访问库中的CodeIgniter本机资源,请使用 get_instance()功能。此函数返回CodeIgniter super 宾语。 通常在您的控制器功能中,您将调用任何一个 可用的CodeIgniter函数使用 $ this 构造。
然而,$ this 只能在您的控制器中直接使用 模型或您的观点。如果您想使用CodeIgniter的类 您可以在自己的自定义类中执行以下操作:
首先,将CodeIgniter对象分配给变量:
$CI =& get_instance();
将对象分配给变量后,您将使用它 变量而不是 $ this :
$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
etc.
希望这会有所帮助。您也可以将$ CI放在构造函数中。
您的代码看起来像这样:
class Tutorial
{
public $CI;
/**
* Constructor.
*/
public function __construct()
{
if (!isset($this->CI))
{
$this->CI =& get_instance();
}
$this->CI->load->database();
}
}