CodeIgniter Forums
Switching databases - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12)
+--- Thread: Switching databases (/showthread.php?tid=62860)



Switching databases - Rashid - 09-03-2015

Is it safe to constantly switch between multiple databases using "USE ..." query? For instance,

$this->db->query("USE webinar_" . $webinar_id);
... do some work ...
$this->db->query("USE main_db");
...
etc.

I wonder is it better to do like this or to maintain several db connections. Dodgy


RE: Switching databases - CroNiX - 09-03-2015

I think its more resource intensive to open a new db connection. I only use multiple connections if there are actually different db servers I'm interfacing with.


RE: Switching databases - Rashid - 09-03-2015

(09-03-2015, 09:19 AM)CroNiX Wrote: I think its more resource intensive to open a new db connection. I only use multiple connections if there are actually different db servers I'm interfacing with.

Ok. Is there any way to use Active Record for that, so i could get rid of pure SQL? AFAIK in 2.2 there is no special method for switching DB's, but maybe in 3+ exists?


RE: Switching databases - mwhitney - 09-03-2015

http://www.codeigniter.com/user_guide/database/connecting.html#connecting-to-multiple-databases

PHP Code:
$db1 $this->load->database('group_one'true);
$db2 $this->load->database('group_two'true);

$db1->query('select something from db1');
$result1 $db1->result();

$db2->query('select something from db2');
$result2 $db2->result(); 

or, if the connections are the same and just the database is different...
PHP Code:
$this->db->db_select('database1');
$this->db->query('select something from database1');
$result1 $this->db->result();

$this->db->db_select('database2');
$this->db->query('select something from database2');
$result2 $this->db->result(); 



RE: Switching databases - Rashid - 09-03-2015

Thank you! db_select() is what i need.


RE: Switching databases - musheertm - 09-17-2015

(09-03-2015, 12:42 PM)mwhitney Wrote: http://www.codeigniter.com/user_guide/database/connecting.html#connecting-to-multiple-databases


PHP Code:
$db1 $this->load->database('group_one'true);
$db2 $this->load->database('group_two'true);

$db1->query('select something from db1');
$result1 $db1->result();

$db2->query('select something from db2');
$result2 $db2->result(); 

or, if the connections are the same and just the database is different...

PHP Code:
$this->db->db_select('database1');
$this->db->query('select something from database1');
$result1 $this->db->result();

$this->db->db_select('database2');
$this->db->query('select something from database2');
$result2 $this->db->result(); 
good one