簡體   English   中英

Codeigniter - 多數據庫連接

[英]Codeigniter - multiple database connections

我必須從主數據庫中檢索 MySQL 數據庫信息,然后連接到該數據庫,並獲取一些記錄。

我的意思是持有一個數據庫我想加載另一個數據庫。

Codeigniter 可以嗎? 現在我在我的 model 中使用以下代碼行。

function connectDb($credential)
{

    $config['hostname'] = $credential['server'];
    $config['username'] = $credential['username'];
    $config['password'] = $credential['password'];
    $config['database'] = $credential['database'];
    $config['dbdriver'] = "mysql";
    $config['dbprefix'] = "";
    $config['pconnect'] = FALSE;
    $config['db_debug'] = TRUE;
    $config['cache_on'] = FALSE;
    $config['cachedir'] = "";
    $config['char_set'] = "utf8";
    $config['dbcollat'] = "utf8_general_ci";

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

    $DB2->db->select('first_name,last_name');
    $query = $DB2->db->get('person');
    print_r($query);

}

它不工作還有其他方法嗎?

您應該在“application/config/database.php”中提供第二個數據庫信息

通常,您會設置default數據庫組,如下所示:

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

請注意,登錄信息和設置在名為$db['default']的數組中提供。

然后,您可以在新數組中添加另一個數據庫 - 我們稱之為“otherdb”。

$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = "root";
$db['otherdb']['password'] = "";
$db['otherdb']['database'] = "other_database_name";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = TRUE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;

現在,要實際使用第二個數據庫,您必須將連接發送到可以在模型中使用的另一個變量:

function my_model_method()
{
  $otherdb = $this->load->database('otherdb', TRUE); // the TRUE paramater tells CI that you'd like to return the database object.

  $query = $otherdb->select('first_name, last_name')->get('person');
  var_dump($query);
}

那應該這樣做。 連接多個數據庫的文檔可以在這里找到: http ://codeigniter.com/user_guide/database/connecting.html

最好的方法是使用不同的數據庫組。 如果您想像往常一樣繼續使用主數據庫($this->db),只需關閉輔助數據庫的持久連接配置選項。 只有主數據庫才能使用持久連接:

主數據庫

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "database_name";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

輔助數據庫(注意 pconnect 設置為 false)

$db['otherdb']['hostname'] = "localhost";
$db['otherdb']['username'] = "root";
$db['otherdb']['password'] = "";
$db['otherdb']['database'] = "other_database_name";
$db['otherdb']['dbdriver'] = "mysql";
$db['otherdb']['dbprefix'] = "";
$db['otherdb']['pconnect'] = FALSE;
$db['otherdb']['db_debug'] = FALSE;
$db['otherdb']['cache_on'] = FALSE;
$db['otherdb']['cachedir'] = "";
$db['otherdb']['char_set'] = "utf8";
$db['otherdb']['dbcollat'] = "utf8_general_ci";
$db['otherdb']['swap_pre'] = "";
$db['otherdb']['autoinit'] = TRUE;
$db['otherdb']['stricton'] = FALSE;

然后您可以像往常一樣使用輔助數據庫作為數據庫對象,同時使用主數據庫:

// use master dataabse
$users = $this->db->get('users');

// connect to secondary database
$otherdb = $this->load->database('otherdb', TRUE);
$stuff = $otherdb->get('struff');
$otherdb->insert_batch('users', $users->result_array());

// keep using master database as usual, for example insert stuff from other database
$this->db->insert_batch('stuff', $stuff->result_array());

用這個。

$dsn1 = 'mysql://user:password@localhost/db1';
$this->db1 = $this->load->database($dsn1, true);     

$dsn2 = 'mysql://user:password@localhost/db2';
$this->db2= $this->load->database($dsn2, true);     

$dsn3 = 'mysql://user:password@localhost/db3';
$this->db3= $this->load->database($dsn3, true);   

用法

$this->db1 ->insert('tablename', $insert_array);
$this->db2->insert('tablename', $insert_array);
$this->db3->insert('tablename', $insert_array);

它對我來說很好(Codeigniter 3)......

這是默認數據庫:

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mydatabase',
    '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
);

在 database.php 文件的底部添加另一個數據庫

$db['second'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mysecond',
    '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
);

在 autoload.php 配置文件中

$autoload['libraries'] = array('database', 'email', 'session');

默認數據庫通過自動加載數據庫庫可以正常工作,但第二個數據庫通過使用模型和控制器中的構造函數加載和連接......

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

在查看您的代碼時,我唯一看到錯誤的是當您嘗試加載第二個數據庫時:

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

當您想要檢索數據庫對象時,您必須在第二個參數中傳遞TRUE

來自Codeigniter 用戶指南

通過將第二個參數設置為 TRUE(布爾值),函數將返回數據庫對象。

因此,您的代碼應該是:

$DB2=$this->load->database($config, TRUE);

這將使它工作。

default database
$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'test',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    '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
);
another db
$db['database2'] = array(
    'dsn' => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'test_2', // Database name
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    '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
   );

在模型中你必須調用

public function getRecords(){
    // Load database
    $db2 = $this->load->database('database2', TRUE);  

   // Select records from 1st database
   $this->db->select('*');
   $query = $this->db->get('record1');
   $result1 = $query->result_array();  

// Select records from 2nd database
   $db2->select('*');
   $query = $db2->get('record2');
   $result2 = $query->result_array();
   $response = array("response1"=>$result1,"response2"=>$result2);
   return $response;
 }
If you need to connect to more than one database simultaneously you can do so as follows:

$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);

注意:將單詞“group_one”和“group_two”更改為您要連接到的特定組名稱(或者您可以傳遞上述連接值)。

通過將第二個參數設置為 TRUE(布爾值),函數將返回數據庫對象。

訪問https://www.codeigniter.com/userguide3/database/connecting.html了解更多信息。

作為其他答案的補充,如果要更改 model 本身的活動數據庫組,因此不需要使用另一個數據庫連接,請在 model ZA2F2ED4F8EBC2CBB4C21A29DC40AB61D 中使用以下內容:

public function set_database($database)
{
    $CI =& get_instance();
    $CI->db = null;
    $this->load->database($database);
}

從 controller 調用后,如:

$this->my_model->set_database('other_db');

然后,您可以使用其他 model 方法作用於新指定的數據庫組,例如:

$this->my_model->insert($data);

注意:目前,僅使用 codeigniter 3 進行測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM