Skip to content

Instantly share code, notes, and snippets.

@devyfriend
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devyfriend/abc2e478f0468ac36404 to your computer and use it in GitHub Desktop.
Save devyfriend/abc2e478f0468ac36404 to your computer and use it in GitHub Desktop.
CodeIgniter MySQL "on duplicate key update"
source: http://web.archive.org/web/20090221091226/http://codeigniter.com/forums/viewthread/80958/
add function to two files
1st file: /system/database/drivers/mysql/mysql_driver.php and perhaps file mysqli_driver.php too
/**
* ON DUPLICATE UPDATE statement
*
* Generates a platform-specific on duplicate key update string from the supplied data
*
* @author Chris Miller <chrismill03@hotmail.com>
* @since 1.6.2
* @access public
* @param string the table name
* @param array the update/insert data
* @return string
*/
function _escape_table($table)
{
return $table;
}
function _duplicate_insert($table, $values)
{
$updatestr = array();
$keystr = array();
$valstr = array();
foreach($values as $key => $val)
{
$updatestr[] = $key." = ".$val;
$keystr[] = $key;
$valstr[] = $val;
}
$sql = "INSERT INTO ".$this->_escape_table($table)." (".implode(', ',$keystr).") ";
$sql .= "VALUES (".implode(', ',$valstr).") ";
$sql .= "ON DUPLICATE KEY UPDATE ".implode(', ',$updatestr);
return $sql;
}
2nd file: /system/database/DB_active_rec.php
/**
* On Duplicate Key Update
*
* Compiles an on duplicate key update string and runs the query
*
* @author Chris Miller <chrismill03@hotmail.com>
* @since 1.6.2
* @access public
* @param string the table to retrieve the results from
* @param array an associative array of update value
* @return object
*/
function on_duplicate($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->_duplicate_insert($this->_protect_identifiers($this->dbprefix.$table), $this->ar_set );
$this->_reset_write();
return $this->query($sql);
}
how to use:
$data = array(
'id' => 10,
'title' => 'title',
'name' => 'name',
'date' => 'date'
);
$this->db->on_duplicate('mytable', $data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment