CI框架 数据库批量插入 insert_batch()

使用CI框架的AR操作:insert_batch()可以减少访问数据库的次数。一次访问即可。示例1:


$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); 

//生成: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another dat

e')

 1 示例2:
 2 
 3 $one_info = array();
 4 $insert_data = array();
 5 $one_info['role_id'] = 6;
 6 $one_info['operator'] = 'test';
 7 for($i = 0; $i <= 3; $i++) {
 8             $one_info['net_id'] = $i;
 9             $insert_data[] = $one_info;
10 }
11 if (!$this->db->insert_batch(tableA,$insert_data)) {
12       return 3;  
13 }
14 
15 //插入的sql语句是 insert into tableA(role_id,operator,net_id) values(6,'test',0),(6,'test',1),(6,'test',2);

注意:第一个参数包含表名,第二个是一个包含数据的关联数组。

  

猜你喜欢

转载自www.cnblogs.com/zb1690194137/p/11038559.html