I’ve been using the Kohana framework for my PHP projects for a while now. One thing that’s annoying is lack of support for INSERT IGNORE and REPLACE INTO. Now, I understand that these are MySQL-specific, and not supported in other RDBMS, but there are equivalents in Oracle. INSERT IGNORE is commonly used on tables where there is an auto incrementing ID field or just a unique index on a particular column.
Anyway, here’s the code that acts like the Database library’s insert() function but ignores any duplicate key exceptions:
/**
* Inserts the row if it's new and returns the ID, or just returns the
* ID if it already exists. The table must have a column called 'id'
* that is the INTEGER AUTO_INCREMENT PRIMARY KEY style in
* order to return an ID.
**/
function _create_if_not_exists( $table, $row, $needs_id=true ) {
$ret = true;
// Try to insert - if it doesn't exist we'll get an ID of zero
$columns = join( ',', array_keys( $row ) );
$placeholders = join( ',', array_fill( 0, count( $row ), '?' ) );
$q = $this->db->query( "INSERT IGNORE INTO $table ($columns) ".
"VALUES ($placeholders)", array_values( $row ) );
if( $needs_id == true ) {
$ret = $q->insert_id();
if( $ret == 0 ) {
$q = $this->db->getwhere( $table, $row );
if( $q->count() > 0 ) {
$result = $q->result_array( false );
$ret = $result[ 0 ][ 'id' ];
}
}
}
return $ret;
}