[eluser]Unknown[/eluser]
It might have been written before by someone else or in some other way, but as I haven`t been able to find it, I thought I`d share my version of the code.
There are 2 files that you need to edit in order to get the
$this->db->replace_into() function to work:
1.
system\database\drivers\mysql\mysql_driver.php
- find:
Code:
function _insert($table, $keys, $values)
{
return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")";
}
- add after
Code:
// --------------------------------------------------------------------
/**
* Replace into statement
*
* Generates a replace into string from the supplied data
*
* @access public
* @param string the table name
* @param array the update data
* @return string
*/
function _replace_into($table, $data)
{
$append = array();
foreach($data as $key => $val){
$append[] = $key . " = " . $val;
}
return "REPLACE INTO " . $table . " SET " . implode(',',$append);
}
2.
system\database\DB_active_rec.php
- find:
Code:
function insert($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($this->_protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->ar_set), array_values($this->ar_set));
$this->_reset_write();
return $this->query($sql);
}
- add after
Code:
// --------------------------------------------------------------------
/**
* Replace into
*
* Compiles an insert into string and runs the query
*
* @access public
* @param string the table name
* @param array the update data
* @return object
*/
function replace_into($table = '', $set = NULL){
$this->_merge_cache();
if( $set !== NULL )
$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->_replace_into(
$this->_protect_identifiers($table, TRUE, NULL, FALSE),
$this->ar_set);
$this->_reset_write();
return $this->query($sql);
}
I`m hoping it helps some of you and at the same time I hope I can get some tips on how to improve this code.