【发布时间】:2015-05-28 15:50:56
【问题描述】:
我见过this topic 并尝试以这种方式实现,但不幸的是不起作用。
我需要使用 CodeIgniter 动态连接到数据库。此数据库不能是文件application/config/databases.php 中的常量变量。我尝试了两种不同的方式连接到不同的数据库:
第一个是按型号 - 第三个参数为documentation refers。
class users extends CI_Controller
{
public function __construct()
{
parent::_construct();
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['database'] = 'clockin_AlKj';
$config['dbdriver'] = 'mysqli';
$config['dbprefix'] = '';
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$this->load->model('company_model', '', $config);
$this->company = $this->company_model->get();
}
}
这会引发错误:
错误号:1146
表“clockin_admin.company”不存在
选择 * 来自 (
company)文件名:C:\xampp\htdocs\clockin\system\database\DB_driver.php
第二种方式是使用数据库连接。
class users extends CI_Controller
{
public function __construct()
{
parent::_construct();
$this->load->model('company_model');
$this->company = $this->company_model->get();
}
}
class Company_model extends CI_model
{
private $otherDb;
public function __construct()
{
parent::__construct();
$config['hostname'] = 'localhost';
$config['username'] = 'root';
$config['password'] = '';
$config['database'] = 'clockin_AlKj';
$config['dbdriver'] = 'mysqli';
$config['dbprefix'] = '';
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$this->otherDb = $this->load->database($config);
}
public function get()
{
$this->otherDb->get('company')->row();
}
}
这会引发错误:
致命错误:在非对象上调用成员函数 get() C:\xampp\htdocs\clockin\application\models\company_model.php 上线 45
指的是$this->otherDb->get('company')->row();这一行
问题是,如果我验证连接是否已建立,它也会返回错误。
if($this->load->database($config) === FALSE)
echo 'Yes, I could not connect..';
最后,我对文件database.php的配置如下:
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'clockin_admin';
$db['default']['dbdriver'] = 'mysqli';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
【问题讨论】:
标签: php database codeigniter