Lvkz Lvkz - 1 month ago 11
PHP Question

Load database connection data dynamically in Codeigniter

I'm trying to accomplish the following functionality: I have a main connection to a database (inside application/config/database.php: db['default']), and that connections work, it retrieves data, I want to use that data to establish a new connection to a different DB.

Is that possible or I need to create an external PDO connection to handle it?

(I'm using Codeigniter 3.1.0)

Answer

With the help of Touheed Khan I was able to reach the solution of my problem, posting it here because I had to do some workaround of the suggested solution to make it work. The following is how my solution is working right now:

Controller.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Controller extends CI_Controller {
 public $dynamicDB;

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

 public function index() {
  //Somehow retrieve the following information from user.
  $host;
  $user;
  $pass;
  $dbname;
  $port;
  // End of retrieval information from user.

  $this->dynamicDB = array(
   'hostname' => $host,
   'username' => $user,
   'password' => $pass,
   'database' => $dbname,
   'dbdriver' => 'postgre',
   'dbprefix' => '',
   'pconnect' => FALSE,
   'db_debug' => TRUE,
   'port' => $port
  );

  $this->load->model('data_model');
  $result = $this->data_model->select($this->dynamicDB, 
                                      $this->get('id'));
  var_dump($result);
 }
}

Data_model.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Data_model extends CI_Model {
 function __construct(){
  parent::__construct();
 }

 public function returnQuery($query) {
  if ($query->num_rows() > 0) {
   return $query->result();
  } else {
   return array();
  }
 }

 public function select($dynamicDB, $id) {
  $dynamicDB = $this->load->database($dynamicDB, TRUE);

  $dynamicDB->select('*');
  $dynamicDB->where('id', $id);
  $dynamicDB->from('table');

  $query = $dynamicDB->get();
  return $this->returnQuery($query);
 }
}