I am trying to insert a few rows into the MySQL table using Codeigniter and Active Records.
PHP Code
$data = array(\'......\'); //
Not highly recommended but here is a hack to preserve the batch insert (which is more efficient wrt Mysql)
// try to insert as usual first
$this->db->insert_batch('my_table', $data);
// if it fails resort to IGNORE
if($this->db->_error_message())
{
$sql = $this->db->last_query();
$sql = str_replace('INSERT INTO', 'INSERT IGNORE INTO', $sql);
$this->db->query($sql);
}
For batch uploads you might need something more like:
foreach ($data as $data_item) {
$insert_query = $this->db->insert_string('my_table', $data_item);
$insert_query = str_replace('INSERT INTO', 'INSERT IGNORE INTO', $insert_query);
$this->db->query($insert_query);
}
UPDATE: Use dcostalis's version (in the comments below this one), it will scale much better :-)
For this purpose i made this helper function:
function insert_batch_string($table='',$data=[],$ignore=false){
$CI = &get_instance();
$sql = '';
if ($table && !empty($data)){
$rows = [];
foreach ($data as $row) {
$insert_string = $CI->db->insert_string($table,$row);
if(empty($rows) && $sql ==''){
$sql = substr($insert_string,0,stripos($insert_string,'VALUES'));
}
$rows[] = trim(substr($insert_string,stripos($insert_string,'VALUES')+6));
}
$sql.=' VALUES '.implode(',',$rows);
if ($ignore) $sql = str_ireplace('INSERT INTO', 'INSERT IGNORE INTO', $sql);
}
return $sql;
}
It can do batch insert and batch insert with ignore. To avoid duplicate rows you must set a unique key in the database table for a primary field.
Using the technique of your second idea, you could generate a query by looping over the array and using:
$this->db->query($query_string);
Don't use insert_batch
, as it actually runs the query. You want insert_string
$insert_query = $this->db->insert_string('my_table', $data);
$insert_query = str_replace('INSERT INTO','INSERT IGNORE INTO',$insert_query);
$this->db->query($insert_query);
UPDATE: This doesn't work for batch queries, only one row at a time.
If still someone is struggling with insert_batch to use ignore,
Check this path,
system/database/DB_query_builder.php
Search for function
protected function _insert_batch
Change
INSERT INTO => INSERT IGNORE INTO
Thank me later. :)