2011-07-12 45 views
1

我将这段代码放在模型类的构造函数中,基于CI的教程,它声明如果你把它放在那里,那么数据库连接可以在那个类中在全局范围内使用。由于某些原因,它不起作用,应用程序在代码的那部分崩溃。我的数据库配置没问题,因为当我把它放在控制器中时,我能够很好地获取数据库信息。

+0

请澄清并清理您的问题。 – 2011-07-12 16:38:36

+0

对于谁投票结束这件事,因为这不是一个真正的问题,我向你保证,这是一个有价值的问题。 – cwallenpoole

+0

如果没有解决方案适用于您,请注意,当我修改了我的配置项安装以允许在Eclipse中自动完成时,我的db启动失败。 –

回答

1

你不需要初始化。好喜欢这个

$autoload['libraries'] = array('database'); 
0

的代码行它配置到
application - config - autoload.php文件来加载数据库对象是:

$this->load->database(); 

数据库对象,然后用名称DB像这样引用:

$this->db->method_name(); 

正如前一篇文章指出的那样,如果要在多个模型中使用数据库,y ou应该在autoload.php配置文件中自动加载库。

0

你是在父类的构造函数之前还是之后这样做?

public function __construct() 
{ 
    // placing it here fails: $this has no `load` property yet. 
    // $this->load->database(); <!-- NO WAY JOSÉ! 
    parent::__construct(); 
    // placing it here should work as the parent class has added that property 
    // during it's own constructor 
    $this->load->database(); 
} 

在另一方面,你可能会更加明确:

public function __construct() 
{ 
    // Doesn't matter where this goes: 
    // grab the controller directly 
    $CI =& get_instance(); // & is not strictly necessary, but still... 
    // force the loader to load the database. 
    $CI->load->database(); 
    // directly assign it. 
    $this->db = $CI->db; 
    // continue on your merry way 
    parent::__construct(); 
} 

我认为明确的解决方案解决了许多问题在PHP 4项目一次,但它在技术上是矫枉过正。