我正在重写我的应用程序以使用CodeIgniter。目前我正在与数据库作斗争。我已经在config/databases.php
中配置了数据库,但不知道如何在库级别访问它们。
我正在通过autoload.php
加载库:
$autoload['libraries'] = array('database', 'FGMembersite', 'phpmailer', 'formvalidator');
FGMembersite是我用于注册和登录的一个类。
我在login.php
视图中访问了这个类,我有:
if(isset($_POST['submitted']))
{
if($this->fgmembersite->Login())
{
$this->fgmembersite->RedirectToURL("main");
}
}
fgmembersite->Login()
导致:
public function DBLogin()
{
$this->connection = pg_connect("host=localhost port=5432 dbname=".$this->db->database." user=".$this->ci->db->username." password=".$this->db->password."");
但是这里的DBLogin()
不明白什么是db
.我收到类似
Undefined property: FGMembersite::$db
或Trying to get property of non-object
我应该如何在FGMembersite
中访问数据库配置?
您需要使用 CodeIgniter 超级对象从其他库中访问自动加载的库。这样
$ci =& get_instance();
$this->connection = pg_connect("host=localhost port=5432 dbname=" . $ci->db->database .
" user=" . $ci->db->username .
" password=" . $ci->db->password );
看起来您正在尝试在代码中使用此方法,只是您只将其用于username
字段,而不是database
和password
字段。
您可以通过将 ci 实例分配给类构造函数中的类属性来保存它,如下所示:
class Yourclass {
private $ci;
public function __construct() {
$this->ci =& get_instance();
}
public DBLogin() {
$this->connection = pg_connect("host=localhost port=5432 dbname=" .
$this->ci->db->database .
" user=" . $this->ci->db->username .
" password=" . $this->ci->db->password );
}
public somethingElse() {
print_r ($this->ci->db->username);
}
}