【问题标题】:Update Local and Web database from codeigniter website从 codeigniter 网站更新本地和 Web 数据库
【发布时间】:2020-02-11 05:17:27
【问题描述】:

我有一个托管在全球服务器上并连接到全球数据库的 Codeigniter 网站。 我想连接另一个本地托管的数据库(192.168.x.x)。 有什么方法可以实现吗?

【问题讨论】:

标签: database sqlite codeigniter


【解决方案1】:

在现实世界的 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)

连接数据库后,可以进行数据库操作,如下图: 加载“另一个数据库”

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

从“mydefaultdatabase”获取结果

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

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

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(); // 

【讨论】:

  • 感谢您的回复。实际上问题是我需要连接两个不同的数据库。其中,一个在我的本地环境中呈现,另一个在全局环境中呈现。如何连接本地环境数据库(192.168.x.x)
猜你喜欢
  • 2016-11-18
  • 2011-11-13
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 2016-07-28
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多