2

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.

1
  • just mention db name before the table like in your query Commented Jun 21, 2017 at 12:24

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

4 Comments

But how to make sql joins ?
Thanks, I will try it !
just use second database table with database_name.table_name
Hi is it possible to configure the secound database after? So i land on my index, and i get some variables and i want to use those variables to build another database is it possible to do it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.