Pernahkah anda membuat program dengan codeigniter yang mengharuskan anda untuk menyebrang dari suatu database ke database lain ? Biasanya hal ini terjadi karena developer program 1 dan program 2 berbeda, jadi databasenya mau gak digabung :p  Sebenarnya script untuk menggunakan multi database di codeigniter tidak ribet kok. Anda hanya perlu mengatur banyak database di database.php, lalu  memanggilnya seperti anda memanggil database biasa.

Berikut langkah-langkahnya :

  1. Buat pengaturan multi database di database.php

Anda harus mengatur terlebih dahulu database-database yang akan di panggil.

///////////Database 1\\\\\\\\\\\\\\\
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "db_1";
$db['default']['hostname'] = "localhost";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";

///////////Database 2\\\\\\\\\\\\\\\
$db['db_invent']['username'] = "root";
$db['db_invent']['password'] = "";
$db['db_invent']['database'] = "db_2";
$db['db_invent']['hostname'] = "localhost";
$db['db_invent']['dbdriver'] = "mysql";
$db['db_invent']['dbprefix'] = "";
$db['db_invent']['pconnect'] = FALSE;
$db['db_invent']['db_debug'] = TRUE;
$db['db_invent']['cache_on'] = FALSE;
$db['db_invent']['cachedir'] = "";
$db['db_invent']['char_set'] = "utf8";
$db['db_invent']['dbcollat'] = "utf8_general_ci";

///////////Database 3\\\\\\\\\\\\\\\
$db['db_simpeg']['username'] = "root";
$db['db_simpeg']['password'] = "";
$db['db_simpeg']['database'] = "db_3";
$db['db_simpeg']['hostname'] = "localhost";
$db['db_simpeg']['dbdriver'] = "mysql";
$db['db_simpeg']['dbprefix'] = "";
$db['db_simpeg']['pconnect'] = FALSE;
$db['db_simpeg']['db_debug'] = TRUE;
$db['db_simpeg']['cache_on'] = FALSE;
$db['db_simpeg']['cachedir'] = "";
$db['db_simpeg']['char_set'] = "utf8";
$db['db_simpeg']['dbcollat'] = "utf8_general_ci";

$active_group = "default";
$active_record = TRUE;
  1. Panggil Database

Untuk memanggil database pertama, caranya sama seperti biasa. Saya yakin anda sudah tau 🙂 Sedangkan untuk memanggil database kedua, caranya adalah :

$this->db_invent = $this->load->database('tabel2', true);
$this->db_invent->select('field1, field2, ...)->get('tabel2')->row();

Untuk memanggil database ketiga :

$this->db_simpeg = $this->load->database('tabel3', true);
$this->db_simpeg->select('field1, field2, ...)->get('tabel3')->row();

Script diatas bisa anda letakkan di model ataupun controller.

Selamat mencoba 🙂

Jika ada pertanyaan, silahkan diskusi dan ditanyakan disini : Group facebook.

Leave a Reply

Your email address will not be published. Required fields are marked *