CodeIgniter Active Record从一个表插入另一个表

时间:2013-01-27 17:26:15

标签: php mysql codeigniter

使用codeigniter活动记录语法将数据从一个表插入另一个表的语法是什么?我尝试了通常的mysqli查询并且它可以工作,但我想使用CodeIgniter Active Record语法来保持一致性。

我尝试使用这些CodeIgniter Active Record查询,但仍然没有运气:

function insert_into()  
{    
    $this->db->insert('table1');
    $this->db->set('to_column');  
    $this->db->select('from_column');
    $this->db->from('table2');
}

2 个答案:

答案 0 :(得分:13)

我认为最好的办法就是使用get方法从一个表中获取所需的数据,然后使用其中一个查询结果抓取器函数(如result()),使用以下方法逐行遍历行。 insert()方法。

将其放入代码:

$query = $this->db->get('table1');
foreach ($query->result() as $row) {
      $this->db->insert('table2',$row);
}

当然,我认为table1与table2具有完全相同的结构(每列的列名和数据类型相同)。如果不是这种情况,则必须使用赋值将列中的列映射到另一个表,但如果是这种情况,则代码将更宽。

答案 1 :(得分:3)

将$ source_table复制到$ archive_table:

if(($this->db->table_exists($source_table) && ($this->db->table_exists($archive_table)){
    if ($this->db->query("CREATE TABLE $archive_table LIKE $source_table")){
        if($this->db->query("INSERT $archive_table SELECT * FROM $source_table")){
           echo 'copied ok';
        }
     } 
}

比在整个结果集上循环并一次插入一行更新。

相关问题