0

After a user logs in, database credentials are gathered from database.

I need to change database connection to use this credentials on following queries.

I found I can do:

$dsn = 'dbdriver://username:password@hostname/database';
$this->load->database($dsn);

But I am not sure how to do this change in one place and that it applies to next queries and discard config on database.

Any ideas?

Eduardo
  • 1,781
  • 3
  • 26
  • 61
  • please refer this example https://stackoverflow.com/questions/53043800/dynamic-database-switch-codeigniter/53044169#53044169 – Sachin Apr 10 '19 at 04:35
  • you can use multiple DB instace, see https://stackoverflow.com/a/8269596/6309457 – Devsi Odedra Apr 10 '19 at 04:35
  • @DevsiOdedra In my case database connection is dynamic. – Eduardo Apr 10 '19 at 04:39
  • @Sachin interesting example, but how can I make that connection default one over all the application without modifying all the places where load->database is called? – Eduardo Apr 10 '19 at 04:40
  • so you can use as `$dsn3 = 'mysql://user:password@localhost/db3'; $this->db3= $this->load->database($dsn3, true); $this->db3->insert('tablename', $insert_array);` – Devsi Odedra Apr 10 '19 at 04:40
  • @Eduardo try this // close the default connection $this->db->close(); // connect to the other db $this->db = $this->load->database($config, TRUE); – Sachin Apr 10 '19 at 04:46
  • @Sachin I think that might work!, I will keep you posted! – Eduardo Apr 10 '19 at 04:49

2 Answers2

0

First you need declare the 2nd parameter in load->database and create a instance db like this:

$db = $this->load->database($dsn,true); 

Then you can use $db from execute some Query like this

$db->query("Your SQL Code is here");

You can put that code in a local function inside some model or controller class to resolve your needs

0

I usually create model class in codeigniter and define a property called $dbsecond and in construction I assign database to this property

class PanelDb extends CI_Model
{
public $dbsecond;

public function __construct()
{
    $this->dbsecond=$this->load->database('panel', TRUE);
}
}

public function insertData(){
$this->dbsecond->insert(.....);
}

and to use this database in every part of controller I load this class in construction

class Monitor extends CI_Controller {

public function __construct()
{
    parent::__construct();

    $this->load->model('login','model');
    $this->load->model('PanelDb ','panelmodel');
}
}

Then in controller I use

$this->panelmodel->insertData(......)
Shojaeddin
  • 1,851
  • 1
  • 18
  • 16