Skip to content

Instantly share code, notes, and snippets.

@stevenwoodson
Created December 27, 2012 06:10
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save stevenwoodson/4385857 to your computer and use it in GitHub Desktop.
Save stevenwoodson/4385857 to your computer and use it in GitHub Desktop.
Codeigniter DB - Insert on Duplicate Update method Generates a platform-specific insert string from the supplied data, MODIFIED to include ON DUPLICATE UPDATE
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class MY_DB_mysql_driver extends CI_DB_mysql_driver {
final public function __construct($params) {
parent::__construct($params);
}
/**
* Insert_On_Duplicate_Update_Batch
*
* Compiles batch insert strings and runs the queries
* MODIFIED to do a MySQL 'ON DUPLICATE KEY UPDATE'
*
* @access public
* @param string the table to retrieve the results from
* @param array an associative array of insert values
* @return object
*/
function insert_on_duplicate_update_batch($table = '', $set = NULL)
{
if ( ! is_null($set))
{
$this->set($set);
}
if (count($this->ar_set) == 0)
{
if ($this->db_debug)
{
return $this->display_error('db_must_use_set');
}
return FALSE;
}
if ($table == '')
{
if ( ! isset($this->ar_from[0]))
{
if ($this->db_debug)
{
return $this->display_error('db_must_set_table');
}
return FALSE;
}
$table = $this->ar_from[0];
}
$sql = $this->_insert_on_duplicate_update_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set));
$this->_reset_write();
return $this->query($sql);
}
/**
* Insert_on_duplicate_update_batch statement
*
* Generates a platform-specific insert string from the supplied data
* MODIFIED to include ON DUPLICATE UPDATE
*
* @access public
* @param string the table name
* @param array the insert keys
* @param array the insert values
* @return string
*/
private function _insert_on_duplicate_update_batch($table, $keys, $values)
{
foreach($keys as $num => $key) {
$update_fields[] = $key .'='. $values[$num];
}
return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).") ON DUPLICATE KEY UPDATE ".implode(', ', $update_fields);
}
}
?>
@ilikenwf
Copy link

This version seems more up to date than the one on the forums...thanks!

@nateperry
Copy link

This looks like it is exactly what I need but I am having trouble implementing it correctly. I am new to CodeIgniter so I am not 100% sure on how to load this in. Do you have any type of instructions on how to use this?

@vinod81
Copy link

vinod81 commented May 15, 2017

Which location this file store and call ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment