CodeIgniter:INSERT多个记录没有循环

时间:2013-02-18 22:52:27

标签: codeigniter activerecord codeigniter-2

可以在CodeIgniter Active Record中使用多个INSERT记录而不使用forach,foreach等吗?

我目前的代码:

foreach($tags as $tag) {
    $tag = trim($tag);
    $data = array(
        'topic_id'  =>  $topic_id,
        'user_id'   =>  $user_id,
        'text'      =>  $tag
    );
    $this->db->insert('topic_tags', $data);
}

1 个答案:

答案 0 :(得分:62)

Codeigniter活动记录有一个函数insert_batch我认为这就是你需要的

$data = array(
   array(
      'title' => 'My title' ,
      'name' => 'My Name' ,
      'date' => 'My date'
   ),
   array(
      'title' => 'Another title' ,
      'name' => 'Another Name' ,
      'date' => 'Another date'
   )
);

$this->db->insert_batch('mytable', $data); 

// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')

适用于Codeigniter 3.x和Codeigniter 2.2.6

更新的链接

insert_batch() for Codeigniter 3.x

insert_batch() for Codeigniter 2.x