1

Is there any method of performing in insert_batch and if the key already exists, UPDATE that row in codeigniter 3 HMVC ?

I have gone through the documentation and found only insert_batch and update_batch and found from some old discussions but with Codeigniter 2 also when i run on my HMVC it's doesn't work.

how to update the row with duplicate key in active records (MySQL Query : On Duplicate Key Update) ? And what happens if one row fails to be inserted or updated in insert_batch ? All insertion fails or only that row ?

Thank you.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Not a Pwntester
  • 65
  • 1
  • 10
  • Possible duplicate of [INSERT Batch, and if duplicate key Update in codeigniter](https://stackoverflow.com/questions/20755949/insert-batch-and-if-duplicate-key-update-in-codeigniter) – Penguine Jan 18 '19 at 04:35
  • @Penguine i have been tried that solution but it's doesn't work in ci3 .. any solution please ? – Not a Pwntester Jan 18 '19 at 04:41
  • Much better to use trigger than to blow your mind in your code. See some tutorials. – Vijunav Vastivch Jan 18 '19 at 05:12
  • Why you are not using a loop instead of batch insert? – Danish Ali Jan 18 '19 at 05:16
  • @DanishAli, i am already using insert batch , but it's needed checked one by one .. and the data is so many and need a long time ... any idea to solving it guys please ? ... i have been search on google it's seem like they were using old ci version – Not a Pwntester Jan 18 '19 at 05:39
  • Is your problem solved with `insert_batch`? If no then why you are not going with an alternative way? – Danish Ali Jan 18 '19 at 05:44

1 Answers1

0

This can help you

public function updateduplicatebatch($table, $data ) {
     if (empty($table) || empty($data)) return false;
     $duplicate_data = array();

     foreach($data AS $key => $value) {
        $duplicate_data[] = sprintf("%s='%s'", $key, addslashes($value));
     }

     $sql = sprintf("%s ON DUPLICATE KEY UPDATE %s", $this->db->insert_string($table, $data), implode(',', $duplicate_data));

     $this->db->query($sql);
     return $this->db->insert_id();
}

And you arrary should be like

$data = array('name' => $name, 'phone' => $phone, 'age' => $age);
Pixysve
  • 88
  • 12