<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_model extends CI_Model {
/**
* Class constructor
*/
public function __construct()
{
parent::__construct();
}
// -----------------------------------------------------------------------
/**
* Here, we're just dynamically creating a query that
* is in the following format:
*
* INSERT INTO `table` (`field1`, `field2`, ...)
* VALUES ('value1', 'value2', ...)
* ON DUPLICATE KEY UPDATE
* `field1` = 'value1',
* `field2` = 'value2',
* ...
*
* @param string $table The table name
* @param array $data The data to be inserted or updated
* @return void
*/
public function insert_or_update_if_exists( $table, array $data )
{
// Basic parameter validation
if( empty( $table ) )
throw new Exception('Supplied table name cannot be empty.');
if( empty( $data ) )
throw new Exception('Data array cannot be empty.');
// In case there is an existing record, prepare data for update
$update_values = [];
$update_arr = [];
foreach( $data as $k => $v )
{
$update_values[] = $v;
$update_arr[] = sprintf( "`%s` = ?", $k );
}
// Create insert/update SQL
$sql = sprintf(
"%s ON DUPLICATE KEY UPDATE %s",
$this->db->insert_string( $table, $data ),
implode( ',', $update_arr )
);
// Do the insert or update
$this->db->query( $sql, $update_values );
}
// -----------------------------------------------------------------------
}
/* End of file MY_Model.php */
/* Location: /application/core/MY_Model.php */