Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter Active Record insert from one table to another

What is the syntax for inserting data from one table to another table, using codeigniter active record syntax? I tried the usual mysqli query and it works, but I want to use CodeIgniter Active Record syntax for consistency.

I tried playing with these CodeIgniter Active Record queries but still no luck:

function insert_into()  
{    
    $this->db->insert('table1');
    $this->db->set('to_column');  
    $this->db->select('from_column');
    $this->db->from('table2');
}
like image 435
swordfish Avatar asked Jan 27 '13 17:01

swordfish


1 Answers

I think the best thing to accomplish that is fetching the data you want from one table using the get method, then using one of the query results grabber functions (like result() ), iterate over the rows one by one using the insert() method.

Putting this in code:

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

Of course, i suppose that table1 has exactly th same structure as table2 (the same column names and data types for each column). If that is not the case, you will have to map the columns from one table to the another using assignments, but if that is the case your code will be more wide.

like image 181
digfish Avatar answered Nov 03 '22 09:11

digfish