我見過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