从代码点火器网站更新本地和 Web 数据库



我有一个Codeigniter网站,它托管在全局服务器上并连接到全局数据库。 我想连接本地托管的另一个数据库 (192.168.x.x(。 有什么办法可以做到这一点吗?

在实际的CodeIgniter项目中,开发人员需要同时使用多个数据库。这给开发人员带来了独特的挑战。由于这是一个足够常见的问题,CodeIgniter 为此提供了一个简单的解决方案。

为了在 CodeIgniter 项目中使用多个数据库连接,您只需创建多个配置数组来简化多个数据库的使用。

默认配置阵列 以下是默认Codeigniter 数据库配置数组的结构:

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'mydefaultdatabase';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['autoinit'] = FALSE;
$db['default']['stricton'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';

因此,为了创建另一个数据库连接,您应该创建另一个配置数组。此数组必须遵循相同的结构。下面是数组的示例:

$db['anotherdb']['hostname'] = 'XXX.XXX.X.XXX';
$db['anotherdb']['username'] = 'another_user';
$db['anotherdb']['password'] = '';
$db['anotherdb']['database'] = 'anotherdatabase';
$db['anotherdb']['dbdriver'] = 'mysql';
$db['anotherdb']['dbprefix'] = '';
$db['anotherdb']['pconnect'] = TRUE;
$db['anotherdb']['db_debug'] = FALSE;
$db['anotherdb']['cache_on'] = FALSE;
$db['anotherdb']['cachedir'] = '';
$db['anotherdb']['char_set'] = 'utf8';
$db['anotherdb']['dbcollat'] = 'utf8_general_ci';
$db['anotherdb']['swap_pre'] = '';
$db['anotherdb']['autoinit'] = FALSE;
$db['anotherdb']['stricton'] = FALSE;

连接到正确的数据库

此时,示例项目中有两个数据库。若要连接到特定数据库,必须指定数据库名称。这是正确的语法:

this->load->database(anotherdb, TRUE)

连接到数据库后,您可以执行如下所示的 databse 操作:加载"另一个数据库">

$this->legacy_db = $this->load->database(anotherdatabase, true);

从"我的默认数据库"获取结果

$this->legacy_db->select ('*');
$this->legacy_db->from ('mydefaultdatabase');
$query = $this->legacy_db->get();
$result = $query->result ();

现在,如果您需要使用第二个数据库,则必须将连接发送到模型函数中可用的变量:

function db_calling_model_method()
{
$otherdb = $this->load->database('anotherdb', TRUE); // the TRUE paramater tells CI that you'd like to return the database object.
$query = $otherdb->select('column_one, column_two')->get('table');
var_dump($query);
}

关闭连接

CodeIgniter 在确定代码不再需要连接后会关闭数据库连接。但是,作为一种好的做法,开发人员应显式关闭连接。以下是解决此问题的方法:

$this->db->close(); // for default Connection
$this->legacy_db->close(); // 

最新更新