连接到codeigniter中的另一个数据库并插入

时间:2017-09-19 10:31:35

标签: php mysql codeigniter codeigniter-2 codeigniter-3

我正在尝试连接到另一个数据库并插入数据,数据正确插入第一个数据库但未插入第二个数据库中,所有字段在两个表中都相同,下面的代码不插入最新的db,下面是我的型号代码,我很确定控制器和视图都很好,如果需要更多细节,请告诉我。我正在使用codeigniter 2.问题出在评论//插入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);

我收到错误说:

遇到错误

您尚未选择要连接的数据库类型。

2 个答案:

答案 0 :(得分:1)

修改

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

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

另请注意

  

如果您只是,则无需创建单独的数据库配置   需要在同一个连接上使用不同的数据库。您可以   在需要时切换到不同的数据库,如下所示:

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

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

 ^
  Does not have any such property

$DB2->your_function( .. )

答案 1 :(得分:0)

在您的中尝试此操作 的模态

<?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();
  } 
}
?>