drbmhd9583 2017-10-05 11:15
浏览 46
已采纳

在codeigniter 3中切换数据库

I am trying to use / change the database for different organizations / users. In master database, I have db_name for different organizations, I am using the following code to store the db_name in session.

$condition = "subdomain =" . "'" . $data['subdomain'] . "' AND " . "status =1";

$this->db->select('id, db_name');
$this->db->from('sublogin');
$this->db->where($condition);
$this->db->limit(1);

$db_name = $this->db->get()->row()->db_name;

// SET db_name for session
$this->session->set_userdata('db_name', $db_name);

in another model, switch the database

$db_name = $this->session->userdata('db_name');
$this->db->db_select($db_name); 

Its working on localhost but not on my live server, it gives error:

A Database Error Occurred Error Number: 1146 Table 'db694230824.users' doesn't exist

I tried to echo the current database and it says the database is not changed.

echo $this->db->database;
die(); 
  • 写回答

1条回答 默认 最新

  • dousuo2812 2017-10-05 18:24
    关注

    1 solution.

    You can work with multiple databases like this:

    $this->db = $this->load->database('default', TRUE);
    $this->anotherDb = $this->load->database('anotherDb ', TRUE);
    

    Or if you assign the codeigniter super-object:

    public function __construct($params) {
    
       $this->CI = & get_instance();
       $this->CI->db = $this->CI->load->database('default', TRUE);
       $this->CI->anotherDb = $this->CI->load->database('anotherDb', TRUE);
    }
    

    2 solution

    It was working earlier, not 100% sure if it still works, but looks like this bug still exist in CI. Just add 1 line of code at simple_query function in /system/database/DB_driver.php file:

    public function simple_query($sql)
    {
        if ( ! $this->conn_id)
        {
            $this->initialize();
        }
    
        $this->db_select(); // add this
        return $this->_execute($sql);
    }
    

    It should allow you use other databases in models like this:

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

    Don't forget to add other's DBs CONNECTIVITY SETTINGS in /application/config/database.php file in similar way as you have with your default db:

    $db['default'] = array(
        'dsn'   => '',
        'hostname' => 'localhost',
        ...
    );
    
    $db['anotherDb'] = array(
        'dsn'   => '',
        'hostname' => 'localhost',
        ...
    );
    

    CodeIgniter » Docs » Database Reference » Connecting to your Database

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样采集或者其它途径拿到全国最新个体工商户数据
  • ¥20 我是一名大学生,想学习java是自学还是报培训班呢
  • ¥15 pycharm该如何爬取网易云歌曲下的评论?
  • ¥15 java调用sap webservice问题
  • ¥20 如何完全复现何恺明resnet论文里的结果,有代码吗,获得论文中的结果(如下图)
  • ¥15 mysql如果表行行数小于1000条还需要分区吗
  • ¥20 有关matlab自定义特殊算符的问题
  • ¥15 第15届蓝桥杯选拔赛斗鱼养殖场
  • ¥15 在vivado的FIFO使用中,FIFO有没有提供可以输出内部存储空间状态的端口?
  • ¥15 C++ QT内存数据匹配对比指导