Codeigniter Active Record - on duplicate key update
Simply add the following function to your system/database/DBactiverec.php file:
/**
* public function on_duplicate
* Compiles an on duplicate key update string and runs the query
*
* @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);
}
Then call using Active Record notation like so in your model:
$this->db->on_duplicate('database_table', $array);
This will update all details in an array for a row where the primary key already exists. If it doesn't exist, it will add it for you!
Written by Gary Garside
Related protips
2 Responses
Nice ;)
over 1 year ago
·
Where's the definition of your duplicateinsert() function?
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#