Combining results from 2 databases in codeigniter

你离开我真会死。 提交于 2019-12-12 00:56:47

问题


I'm trying to work out how to combine the results from the same table in 2 mysql databases using codeigniter.

Both tables have the same column names, but the databases have different connection settings.

I'm currently trying this:

public function getAllNames() {

$sql1 = <<SQL
        SELECT 
          id, name, CONCAT(name, ' (', id, ')') AS name2
        FROM
          db1.table
        ORDER BY name
SQL;

$sql2 = <<SQL
        SELECT 
          id, name, CONCAT(name, ' (', id, ')') AS name2
        FROM
          db2.table
        ORDER BY name
SQL;

$q = $this->db->query($sql1." UNION ".$sql2);

return $q->result();

}

Storing the same query for each database in 2 variables then trying to combine them using UNION. However, this can't work because it doesn't recognise the db names as databases (and it wouldn't have the connection settings for each db this way anyway). I think the ORDER BYs are in the wrong place here too. I'm not sure where I should specify the db for each query or if this method would work at all.

Any ideas?


回答1:


Try like

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

$res1 = $DB1->query($sql1);
$res2 = $DB2->query($sql2);
$result = array_merge($res1 , $res2);



回答2:


Actually, the accepted answer doesn't work, as the query function doesn't return an array, but a database result object.

As seen on this question, you need to call the result function, that returns an array of objects (or the result_array, that returns an array of arrays), and merge these arrays:

Using result:

$array_1 = $this->db->get()->result();
$array_2 = $this->db->get()->result();
$final_array = array_merge($array_1, $array_2);

foreach ($final_array as $row){
    echo $row->id;
    echo $row->description;
}

Using result_array:

$array_1 = $this->db->get()->result_array();
$array_2 = $this->db->get()->result_array();
$final_array = array_merge($array_1, $array_2);

foreach ($final_array as $row){
    echo $row['id'];
    echo $row['description'];
}


来源:https://stackoverflow.com/questions/18532548/combining-results-from-2-databases-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!