Multiple Databases In Codeigniter

Here is the general transcript from the video, however the video includes a lot more:

Hello, this is Jedidiah Reeser from JedidiahMedia.com. Today, I’m going to show you how to connect to multiple databases in CodeIgniter.

Step 1
I am going to add the secondary database details in the config folder. I will open database.php in the config folder which is found in the application folder. I will copy and paste the database settings and change default to second_db.

Step 2
Next, I will go to the controller and add the code to load the model.

 $this->load->model('example','', TRUE);

Step 3
Then I will go to the model and make it connect to the second database. To do this, I will add a private variable in the class. In the constructor function I will load the second database. I will create a function to run a query using the second database.


class Example extends Model
{
  private $second_db;

  function Example()
  {
      parent::Model();
      $this->second_db = $this->load->database('second_db', TRUE);
  }

function get_latest()
{
    $info = '';
    $query = $this->second_db->query('SELECT * FROM wp_posts limit 3');

    if ($query->num_rows() > 0 ){
      $info .= '<ul>';
       foreach ($query->result() as $row)
        {
            $info .= '
            <li>
              <h3>'.$row->post_title.'</h3>
            <br />
            <div>'.$row->post_excerpt.'</div>
           </li>
            ';
        }
        $info .= '</ul>';
    }

    return $info;

    }
}

Step 4
After that I will open the controller and send the information to the view.

 $this->load->model('example','', TRUE);

 $data['posts'] = '
     <div id="blogposts">
    <h2>Recent Posts</h2>
    ';
    $data['posts'] .= $this->example->get_latest();

    $data['posts'] .= '</div>';

    $this->load->view('welcome_message', $data);

Step 5
Then, I will go to the view and display the information.

    <?=$posts;?>

Thanks for watching! I hope that you have found this video tutorial helpful. For more tips or information, please visit my sites at: jedidiahreeser.com and jedidiahmedia.com. And a special thanks to Krystal Reeser for helping me create this video.

Buy Me a Coffee