Insert Batch Method

The insert_batch method is an alias from Insert Multi method. This method purpose is for inserting multiple rows data into a table.

Basic Usage

Here is the basic usage insert_batch method from $db property on SENE_Model class.

$this->db->insert_batch(string $table_name, array $data_inserts [, bool $is_debug = 0]): boolean

Parameters

This method has 2 required parameters and 1 optional parameter.

$table_name

The $table_name refers to the name of the table to which the data is to be inserted.

$data_inserts

The $data_inserts value can contain 2 dimension array. The first dimension array are the data sequencer. Each data sequencer contain an array with key value pair. The array key refer to column name of the table and the value refer to value that will be inserted. This value supported MySQL builtin functions and values, such as:

  • NOW()
  • NULL

Examples

This examples will show implementation insert_batch method on class model and then how to executing the method on controller class.

The Model Class Example

Here is the source code example for Blog_Model class.

class Blog_Model extends SENE_Model{
  var $tbl = 'blog';
  var $tbl_as = 'b';

  public function __construct(){
    parent::__construct();
  }
  ...
  public function inserts($dis){
    $this->db->insert_batch($ths->tbl,$dis);
  }
  ...
}

The Controller Class Example

Here is the source code for controller class example using insert_batch method.

class Blog extends SENE_Controller{
  public function __construct(){
    parent::__construct();
    $this->load('blog_model','bm'); #class scope model
  }
  public function index(){
    $id = 1;
    $di = array();

    $dis = array();
    $dis['id'] = 1;
    $dis['title'] = "This is new title of this blog!";
    $dis['content'] = "This is new title of this blog!";
    $dis['date_publish'] = "NULL";
    $di[]=$dis;

    $dis = array();
    $dis['id'] = 2;
    $dis['title'] = "Test multiple insert";
    $dis['content'] = "This is new test for multiple insert";
    $dis['date_publish'] = "NOW()";
    $di[]=$dis;

    $res = $this->bm->inserts($id,$dis); //call the method on the model
    if($res){
      echo 'Success';
    }else{
      echo 'failed';
    }
  }
}

SQL Result

The following is the SQL command that generated from Blog controller while executing insert_batch method.

INSERT INTO blog (id,title,content,date_publish)
VALUES
  (1,"This is new title of this blog!","This is new title of this blog!",NULL),
  (2,"Test multiple insert","This is new test for multiple insert",NOW())
;