I'm doing something like that, same code but different databases depending on the subdomain.
I have a database with a table for domains, mapping a 'domain' to 'dbname':
CREATE TABLE IF NOT EXISTS `empresas` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`database` char(10) NOT NULL,
`active` tinyint(1) NOT NULL,
`domain` char(255) NOT NULL
PRIMARY KEY (`id`),
KEY `domain` (`domain`)
) ;
then an abtract controller base class that makes the magic:
<?php
class AB_Base_Controller extends CI_Controller {
public $empresa;
public function __construct() {
parent::__construct();
$this->empresa = $this->session->userdata('empresa');
if ($this->empresa === FALSE || empty($this->empresa)) {
$this->load->model('sistema_model', 'sistema');
$this->empresa = $this->sistema->get_empresa();
$this->session->set_userdata('empresa', $this->empresa );
}
// configure the client database
$db['hostname'] = 'localhost';
$db['username'] = "whatever";
$db['password'] = "whatever";
$db['database'] = 'tqm'.$this->empresa['database']; // the 'tqm' at the beginning is just for make difference with the rest of db
$db['dbdriver'] = 'mysql';
$db['dbprefix'] = '';
$db['pconnect'] = TRUE;
$db['db_debug'] = FALSE; //TRUE;
$db['cache_on'] = FALSE;
$db['cachedir'] = '';
$db['char_set'] = 'iso-8859-1';
$db['dbcollat'] = 'latin1_swedish_ci';
$db['swap_pre'] = '';
$db['autoinit'] = TRUE;
$db['stricton'] = FALSE;
$this->load->database($db, FALSE, TRUE);
}
}
any controller that inherits that will have the db configured.
the model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// CI 2.0 Compatibility
if(!class_exists('CI_Model')) { class CI_Model extends Model {} }
class Sistema_model extends CI_Model
{
/**
* Contiene el nombre de la tabla en la que se guardan los datos del dominio y la empresa cliente asociada
*
* @var string
**/
public $table = 'empresas';
public function __construct()
{
parent::__construct();
}
/**
* Retorna la empresa basado en los datos de conexión
*
* @return array
**/
public function get_empresa()
{
$query = $this->db->select( 'id, database' )
->where('active', 1)
->where('domain',$_SERVER['SERVER_NAME'])
->get($this->table);
if( $query->num_rows() == 0 ) redirect('http://www.google.com');
$result = $query->first_row('array');
return $result;
}
}
Sorry by the lenght, but the code will explain better than my poor english.