ci框架 动态选择数据库

1.问题:按照手册动态选择数据库时,一直切不过去


2.解决方式:

我先大致描述下:

a.在application\config\autoload.php文件中将修改配置:

$autoload['libraries'] = array('database');//在每一个页面加载时自动实例化数据库类

b.application\config\database.php配置多个数据库:

$db['demodb'] = array(
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'test',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => TRUE,
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);


$db['analysis'] = array(
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'sys_user',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => TRUE,
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

c.新建model文件:

load->database('analysis', true);
	//var_dump($this->load->database('analysis', true));
    }

    public function get_last_ten_entries()
    {
	//var_dump($this->db);
        $query = $this->db->get('main_user', 10);
        return $query->result();
    }
}


d.在控制器中选用model:

$this->load->database('analysis', TRUE);
$this->load->model('main_model');
var_dump($this->main_model->get_last_ten_entries());

结果是一直报错。因为当前的database数据库还是在初始配置默认数据库,即在database.php中 $active_gruop 选择的数据库

解决过程:

先打印:  

 $this->load->database('analysis', true);  

返回确实是我选择数据库,然后我再model中再打印下

($this->db);  显示的是默认选择的数据库。
 

于是只要改成

$this->db = $this->load->database('analysis', true);
就可以访问成功了。




你可能感兴趣的:(CI)