Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT IGNORE using Codeigniter

I am trying to insert a few rows into the MySQL table using Codeigniter and Active Records.

PHP Code

$data = array('......');  // some rows of data to insert $this->db->insert_batch('my_table', $data); 

However this may cause duplicate rows to be inserted into the table. To handle the insertion of duplicate data, I plan to use the INSERT IGNORE command to not insert the row if the row is a duplicate.

Problem: I cannot find the INSERT IGNORE equivalent in Active Records and do not want to edit the Active Record class. Are there any other alternatives?

The following looks interesting, but if I do the following, wont the query be run twice?

$insert_query = $this->db->insert_batch('my_table', $data);  // QUERY RUNS ONCE $insert_query = str_replace('INSERT INTO','INSERT IGNORE INTO',$insert_query); $this->db->query($insert_query); // QUERY RUNS A SECOND TIME 
like image 845
Nyxynyx Avatar asked Jun 10 '12 01:06

Nyxynyx


People also ask

How to use insert IGNORE IN CodeIgniter?

$data = array('......'); // some rows of data to insert $this->db->insert_batch('my_table', $data); However this may cause duplicate rows to be inserted into the table. To handle the insertion of duplicate data, I plan to use the INSERT IGNORE command to not insert the row if the row is a duplicate.

What is insert ignore into?

The INSERT IGNORE command keeps the first set of the duplicated records and discards the remaining. The REPLACE command keeps the last set of duplicates and erases out any earlier ones. Another way to enforce uniqueness is to add a UNIQUE index rather than a PRIMARY KEY to a table.


1 Answers

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.

like image 72
Rocket Hazmat Avatar answered Sep 19 '22 22:09

Rocket Hazmat