How to insert records using select in codeigniter active record

vikmalhotra picture vikmalhotra · Jul 29, 2010 · Viewed 22.2k times · Source

I want to implement a sql query using CodeIgniter Active Record class. The query looks like this..

INSERT california_authors (au_id, au_lname, au_fname)
SELECT au_id, au_lname, au_fname
FROM authors
WHERE State = 'CA'

Is this possible in CodeIgniter without using the $this->db->query method?

Solution:

$this->db->select('au_id, au_lname, au_fname');
$this->db->from('california_authors');
$this->db->where('state', 'CA');
$query = $this->db->get();

if($query->num_rows()) {
    $new_author = $query->result_array();

    foreach ($new_author as $row => $author) {
        $this->db->insert("authors", $author);
    }           
}

Regards

Answer

Edgar Nadal picture Edgar Nadal · Jul 29, 2010

I think you are talking about a a SELECT ... INSERT query, on the active record class there is not a method to do that, but there are two ways to do it

1)

$query = $this->db->query('INSERT california_authors (au_id, au_lname, au_fname)
                           SELECT au_id, au_lname, au_fname
                           FROM authors
                           WHERE State = \'CA\'');

As you say

And 2) you can can do this, using what Calle said,

$select = $this->db->select('au_id, au_lname, au_fname')->where('state', 'CA')>get('california_authors');
if($select->num_rows())
{
    $insert = $this->db->insert('california_authors', $select->result_array());
}
else
{ /* there is nothing to insert */