sunshine
sunshine

Reputation: 381

connect to another db in codeigniter and insert

i am trying to connect to another db and insert data , data is properly inserting in the first db but does not insert in the second db , all the fields being the same in both the tables , the code below does not insert in the latestdb, below is my model code, I am quite sure that controller and views are fine , Please let me know if more details are required. I am using codeigniter 2. The problem is after the comment // Insert in pr_users

$this->db->$function($this->myTables['users'], $data);
				$db1['latestdb']['hostname'] = 'localhost';
				$db1['latestdb']['username'] = 'root';
				$db1['latestdb']['password'] = 'passw';
				$db1['latestdb']['database'] = 'latestdb';
				$db1['latestdb']['dbdriver'] = 'mysql';
				$db1['latestdb']['dbprefix'] = '';
				$db1['latestdb']['pconnect'] = TRUE;
				$db1['latestdb']['db_debug'] = TRUE;
				$db1['latestdb']['cache_on'] = FALSE;
				$db1['latestdb']['cachedir'] = '';
				$db1['latestdb']['char_set'] = 'utf8';
				$db1['latestdb']['dbcollat'] = 'utf8_general_ci';
				$db1['latestdb']['swap_pre'] = '';
				$db1['latestdb']['autoinit'] = TRUE;
				$db1['latestdb']['stricton'] = FALSE;
			
			
				$DB2 = $this->load->database($db1, TRUE);
				$DB2->db_select('zipbizzlatestdb');
				$DB2->$function($this->myTables['users'], $data);

				$DB2->insert('pr_users',$data);

I am getting error saying :

An Error Was Encountered

You have not selected a database type to connect to.

Upvotes: 1

Views: 2297

Answers (2)

Jawahar Sharma
Jawahar Sharma

Reputation: 127

Try this in your Modal

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

class Test extends CI_Model {

  function __construct()
  {
    parent::__construct();
    $this->another = $this->load->database("anotherdb",true);
  } 

  function get()
  {
    $this->another->select("*");
    $this->another->from("admin");
    $query = $this->another->get();
    return $query->result();
  } 
}
?>

Upvotes: 0

Akshay Hegde
Akshay Hegde

Reputation: 16997

Modify

$DB2 = $this->load->database($db1);

To

// TRUE parameter tells CI that you'd like to return the database object.
$DB2 = $this->load->database($db1, TRUE);

Also note

You don’t need to create separate database configurations if you only need to use a different database on the same connection. You can switch to a different database when you need to, like this:

$this->db->db_select('database2_name');

and

$this->$DB2->your_function( ... )

 ^
  Does not have any such property

To

$DB2->your_function( .. )

Upvotes: 1

Related Questions