php - 使用 codeIgniter 查询多个数据库

标签 php mysql database codeigniter multiple-databases

我有 2 个数据库,我想使用这 2 个数据库进行查询,例如

SELECT base1.table1.item1 FROM base1.table1 INNER JOIN base2.table3 ON base2.table3.item2 = base1.table1.item2 WHERE base2.table3.item4 = 'toto';

如何使用 codeIgniter 进行此查询? 我已经在 CodeIgniter 中使用 2 个数据库配置了 database.php。

谢谢。

最佳答案

You can setup 2 database in config/database.php file

$active_group = 'default';
$query_builder = TRUE;

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

//set second db configuration 
$db['otherdb'] = array(
'dsn'   => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'second_db',
'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

);

When you want use default database means master database

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

// connect to secondary database
 $otherdb = $this->load->database('otherdb', TRUE);
 $data = $otherdb->get('table_name');

if your first db name is base1 and second is base2

$this->db->select('table1.item1 FROM table1');
                 $this->db->from('table1');
                 $this->db->join('base2.table3', 'base2.table3.item2 =table1.item2');
$this->where('base2.table3.item4','toto')
$query = $this->db->get();

关于php - 使用 codeIgniter 查询多个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44675797/

相关文章:

php - 如何将 pptx 和 ppt 转换为 pdf 和 swf

mysql - SQL 在执行 select unique/group by 时根据键选择特定行

javascript - Mongoose 在两个参数中搜索一个值

php - 如何编写查询来选择相似的标题?

php - 如何在xml和php中只查询一个节点?

mysql - sql查询与当天比较

mysql - 核心数据和 MySQL

java - MySQL 命令在列中选择值 - JDBC

database - sqlite3 从空表中选择 = 不选择?

php - 我在 php 上使用 ajax 发送的值时总是出现错误