我见过this topic并试图实现这种方式,不幸的是不工作。CodeIgniter动态数据库不工作
我需要使用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();
}
}
这引发错误:
Error Number: 1146
Table 'clockin_admin.company' doesn't exist
SELECT * FROM (
company
)Filename: 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();
}
}
这引发错误:
Fatal error: Call to a member function get() on a non-object in C:\xampp\htdocs\clockin\application\models\company_model.php on line 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;
它仍然无法正常工作。它继续将数据库集合在'database.php'文件中。 '$ this-> otherDb = $ this-> load-> database('mysql:// root:@localhost:9090/clockin_AlKj',TRUE);' – Linesofcode
你确定吗?我刚刚测试过这种方法。也许你的密码字符串包含一些可能会使解析器混淆的符号?另外,你的服务器真的在端口9090上运行?如果它是默认端口,则不需要指定它。 – emiliopedrollo
您是否将get方法转换为$ this-> otherDb-> get('company') - > row(); ? – emiliopedrollo