How to insert records using select in codeigniter active record
我想使用CodeIgniter Active Record类来实现sql查询。查询看起来像这样。.
1 2 3 4 | INSERT california_authors (au_id, au_lname, au_fname) SELECT au_id, au_lname, au_fname FROM authors WHERE State = 'CA' |
是否可以在CodeIgniter中使用$ this-> db-> query方法?
解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 | $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); } } |
致谢
我认为您正在谈论的是SELECT ... INSERT查询,在活动记录类上没有做到这一点的方法,但是有两种方法可以做到这一点
1)
1 2 3 4 | $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\''); |
如您所说
然后2)您可以使用Calle所说的进行操作,
1 2 3 4 5 6 7 | $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 */ |
如果要对查询执行进行良好控制,则可以通过3种方式进行SELECT ... INSERT:
1)使用代码点火器活动记录insert_batch(ci3)或insertBatch(ci4)(推荐):
1 2 3 4 5 6 7 | $select = $this->db->select('au_id, au_lname, au_fname')->where('state','CA')>get('california_authors'); if($select->num_rows()) { $insert = $this->db->insert_batch('california_authors', $select->result_array()); } else { /* there is nothing to insert */} |
2)使用codeigniter活动记录简单插入:
1 2 3 4 5 6 7 8 | $select = $this->db->select('au_id, au_lname, au_fname')->where('state','CA')>get('california_authors'); if($select->num_rows()) { foreach($select->result_array() as $row) $this->db->insert('california_authors', $row); } else { /* there is nothing to insert */} |
3)使用codeigniter活动记录查询执行:
1 2 3 4 | $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\''); |
这是一个旧帖子,但这对某人可能有用。
与Edgar Nadal答案相同,只是将参数传递给查询的更安全方式
1 2 3 4 5 6 7 8 | $state = 'CA'; $sql =" INSERT california_authors (au_id, au_lname, au_fname) SELECT au_id, au_lname, au_fname FROM authors WHERE State = ? "; $this->db->query($sql, array($state)); |
codeigniter-3.2.1
1 2 3 | $query = $this->db->insert('california_authors', array('au_id' => 'value', 'au_lname' => 'value', 'au_name' => 'value')); $query2 = $this->db->select('au_id, au_lname, au_fname')->where('state', 'CA')->get('california_authors'); |
要检索结果,可以执行以下操作:
1 | $resultarr = $query->result_array(); // Return an associative array |
手册中对此有很多信息。
http://codeigniter.com/user_guide/database/active_record.html