How to Connect Multiple Databases in Codeigniter



Good evening guys, how are you? After all this time we come back again and this time we will discuss how to make connections to several databases on CodeIgniter.

If you have not installed the latest codeigniter, please click on this link, you will immediately be redirected to the official website. then you need to install it by opening application / config / config.php in the CodeIgniter file that you downloaded, and at the end of this post you can directly download this file.

 $config['base_url'] = 'http://localhost/multipledb'; 

The first time we have to prepare is a database, according to the title of this post that we made two databases, mydab and second. The contents of the table from both databases are the same.

mydab
 CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data untuk tabel `members`
--

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Arman', 'Basir', 'Malino'),
(2, 'Abidzar', 'Alif', 'Pettarani');
 

second
 CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data untuk tabel `members`
--

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(3, 'Andi', 'Alif', 'Pengayoman'),
(4, 'Dede', 'Ahmad', 'Alauddin'); 

Configuring database connection
You just need to open application / config / database.php and configure the database connection according to the one below.
 $db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'mydab',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => TRUE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

$db['second'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'second',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => TRUE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);
 

Create Models
You only need to open the application / models then create a file with the name Members_model.php and Seconddb_model.php

Members_model.php
 <?php
 class Members_model extends CI_Model {
  function __construct(){
   parent::__construct();
   $this->load->database();
  }
 
  public function getUsers(){
   $query = $this->db->get('members');
   return $query->result(); 
  }
 
 }
?> 

Seconddb_model.php
 <?php
 class Seconddb_model extends CI_Model {
  function __construct(){
   parent::__construct();
   //load our second db and put in $db2
   $this->db2 = $this->load->database('second', TRUE);
  }
 
  public function getsecondUsers(){
   $query = $this->db2->get('members');
   return $query->result(); 
  }
 
 }
?> 

Creating Controller
You only need to open the application / controllers then create a file named Main.php
 <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Main extends CI_Controller {
 function __construct(){
  parent:: __construct();
  $this->load->helper('url');
  //load default database
  $this->load->model('members_model');
  //load second database
  $this->load->model('seconddb_model');
 }
 
 public function index(){
  //default database data
  $data['firsts'] = $this->members_model->getUsers();
  //second database data
  $data['seconds'] = $this->seconddb_model->getsecondUsers();
  $this->load->view('show', $data);
 }

}
 

Creating View
Create thefiles inside application/views folder Then create a file with the name show.php. To make this view we use bootstrap,
 <!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>How to connect to multiple database in CodeIgniter</title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
</head>
<body>
 <nav class="navbar navbar-default navbar-static-top">
  <div class="container-fluid">
   <div class="navbar-header">
    <a class="navbar-brand" href="https://www.tutorialswb.com/">TutorialsWB</a>
    <ul class="nav navbar-nav">
     <li class="active"><a href="#">Connect Multiple Databases</a></li>
    </ul>
   </div>
  </div>
 </nav>
 <div class="container">
  <div class="row">
   <div class="col-sm-6 col-sm-offset-3">
    <h3>Default Database</h3>
    <table class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>ID</th>
       <th>Firstname</th>
       <th>Lastname</th>
       <th>Address</th>
      </tr>
     </thead>
     <tbody>
      <?php
     //$data['firsts'] from our controller
      foreach($firsts as $first){
       ?>
       <tr>
        <td><?php echo $first->id; ?></td>
        <td><?php echo $first->firstname; ?></td>
        <td><?php echo $first->lastname; ?></td>
        <td><?php echo $first->address; ?></td>
       </tr>
       <?php
      }
      ?>
     </tbody>
    </table>
   </div>
  </div>
  <div class="row">
   <div class="col-sm-6 col-sm-offset-3">
    <h3>Second Database</h3>
    <table class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>ID</th>
       <th>Firstname</th>
       <th>Lastname</th>
       <th>Address</th>
      </tr>
     </thead>
     <tbody>
      <?php
     //$data['seconds'] from our controller
      foreach($seconds as $second){
       ?>
       <tr>
        <td><?php echo $second->id; ?></td>
        <td><?php echo $second->firstname; ?></td>
        <td><?php echo $second->lastname; ?></td>
        <td><?php echo $second->address; ?></td>
       </tr>
       <?php
      }
      ?>
     </tbody>
    </table>
   </div>
  </div>
 </div>
</body>
</html> 

You can download it by pressing the button below.


Hopefully what we share is useful for you, especially for friends who are just learning.

No comments:

Post a Comment