2013-05-30 173 views
1

我是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

使用一个模型,它会在那里工作。 – tomexsans

+0

定义“load”在哪里? – Jocelyn

+0

使用了一个模型,给了我几乎相同的错误消息,除了这次致命错误读取'调用一个非对象'上的成员函数模型()。所以我既不能加载数据库()也不能加载模型()。应该是负载问题吗? –

回答

5

变化

$this->load->database(); 

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

数据库不是一个直接的方法。它是codeigniter中的一个库,您必须将其作为库加载。

您也可以在autoload.php中自动加载database库。

UPDATE:

您正在使用您的类和方法的名称相同。在PHP4中,具有相同的名称作为类名称的方法被视为构造,但如果你使用的是笨2+,你必须使用PHP5的构造函数是

function __construct() 
{ 
    parent::__construct(); 
    /*Additional code which you want to run automatically in every function call */ 
} 

你不能给的方法相同的名称, Codeigniter 2+中的类名称。将该方法更改为其他任何内容。如果您希望默认加载,可以命名方法index

这应该可以解决您的问题。

+0

'$ this-> load-> library('database')'仍然给我提供相同的错误信息,除了这次错误信息用'library()'替换'database()'。我想这个问题应该是'load',因为我使用了一个模型,并且错误消息仍然出现,这次指向'model()',即:'致命错误:调用成员函数模型()非对象。“仍然无法修复它。现在已经有几个小时了。 –

+0

您是否更改过任何系统核心文件? – sakibmoon

+0

什么是您的PHP版本号?你在Tutorial Class中有一个构造函数吗?如果是,发布代码。 – sakibmoon

2

CodeIgniter用户指南,Creating Libraries科:

To access CodeIgniter's native resources within your library use the get_instance() function. This function returns the CodeIgniter super object. Normally from within your controller functions you will call any of the available CodeIgniter functions using the $this construct.

$this, however, only works directly within your controllers, your models, or your views. If you would like to use CodeIgniter's classes from within your own custom classes you can do so as follows:

First, assign the CodeIgniter object to a variable:

$CI =& get_instance(); 

Once you've assigned the object to a variable, you'll use that variable instead of $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(); 
    } 
}