Search code examples
phpmysqldatabasecodeignitermultiple-databases

Queries on multiple database with codeIgniter


I have 2 databases, and I would like to make a query with the 2 databases, like for example

SELECT base1.table1.item1 FROM base1.table1 INNER JOIN base2.table3 ON base2.table3.item2 = base1.table1.item2 WHERE base2.table3.item4 = 'toto';

How to make this query with codeIgniter ? I already have configured database.php in CodeIgniter with the 2 databases.

Thanks.


Solution

  • You can setup 2 database in config/database.php file

    $active_group = 'default';
    $query_builder = TRUE;
    
    $db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'first_db',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
    );
    
    //set second db configuration 
    $db['otherdb'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'second_db',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
    

    );

    When you want use default database means master database

    // use master dataabse
    $users = $this->db->get('users');
    
    // connect to secondary database
     $otherdb = $this->load->database('otherdb', TRUE);
     $data = $otherdb->get('table_name');
    

    if your first db name is base1 and second is base2

    $this->db->select('table1.item1 FROM table1');
                     $this->db->from('table1');
                     $this->db->join('base2.table3', 'base2.table3.item2 =table1.item2');
    $this->where('base2.table3.item4','toto')
    $query = $this->db->get();