我在我的CI应用程序上使用了两个不同的数据库。
我在mysql上创建了2个用户,并将user1授予db1所有权限,然后将user2授予db2与SQLpro客户端的所有权限。
database.php:
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = '***1';
$db['default']['password'] = '***1';
$db['default']['database'] = 'ci_users';
$db['default']['dbdriver'] = 'mysql';
$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_unicode_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
$db['keys']['hostname'] = 'localhost';
$db['keys']['username'] = '***2';
$db['keys']['password'] = '***2';
$db['keys']['database'] = 'ci_keys';
$db['keys']['dbdriver'] = 'mysql';
$db['keys']['dbprefix'] = '';
$db['keys']['pconnect'] = TRUE;
$db['keys']['db_debug'] = TRUE;
$db['keys']['cache_on'] = FALSE;
$db['keys']['cachedir'] = '';
$db['keys']['char_set'] = 'utf8';
$db['keys']['dbcollat'] = 'utf8_unicode_ci';
$db['keys']['swap_pre'] = '';
$db['keys']['autoinit'] = TRUE;
$db['keys']['stricton'] = FALSE;
模特:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_Users extends CI_Model {
function Model_Users()
{
// Call the Model constructor
parent::__construct();
$this->load->database('default',true);
}
etc...
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_Keys extends CI_Model {
function Model_Keys()
{
// Call the Model constructor
parent::__construct();
$this->load->database('keys',true);
}
etc...
因此,当在同一个控制器/方法中使用两个模型时,model_users工作得很好但是model_keys返回一个错误,因为它似乎无论如何加载了model_users db1而不是db2:
无法修改标头信息 - 已经发送的标头(输出从/Applications/XAMPP/xamppfiles/htdocs/app/application/models/model_keys.php:2开始) 文件名:core / Common.php
行号:442
发生数据库错误
错误号码:1146
表'ci_users.ci_keys'不存在//这应该是ci_keys.ci_keys
有人有想法吗?
我在model_keys中编辑了代码:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_Keys extends CI_Model {
function Model_Keys()
{
// Call the Model constructor
parent::__construct();
$this->db_keys = $this->load->database('keys',true);
}
现在db工作但我在模型上收到会话错误:
消息:无法修改标头信息 - 已经发送的标头(输出从/Applications/XAMPP/xamppfiles/htdocs/site/application/models/model_keys.php:2开始)
在控制器中我这样做:
$this->load->model('model_users');
$this->model_users->insert(bla bla);
$this->load->model('model_keys');
$this->model_keys->insert(bla bla);
$this->session->set_userdata(array(bl bla);
redirect(some url);
答案 0 :(得分:3)
下面是问题
$this->load->database('keys',true);
如果您传递第二个参数TRUE,那么它将返回数据库对象,它将无法与ActiveRecord一起使用。
这是示例
$DB1 = $this->load->database('group_one', TRUE);
//Then you can't below function
$this->db->query();
You will instead use:
$DB1->query();