I have created this model for Codeigniter. It's working fine, but I need to know if it can be more optimized.
class Basic_Function_Model extends CI_Model
{
var $msg_invalid_array;
var $msg_no_table;
function __construct()
{
parent::__construct();
$this->msg_invalid_array = "Data must be provided in the form of array";
$this->msg_no_table = "Table does not exist in database";
$this->load->database();
}
public function insertInDatabase($table, $insertData, $mode = "single")
{
if( !is_array($insertData) ) {
return $this->msg_invalid_array;
}
if( !$this->validateTable($table) ) {
return $this->msg_no_table;
}
if( $mode == "batch" ) {
return $this->db->insert_batch($table, $insertData);
} else {
$this->db->insert($table, $insertData);
return $this->db->insert_id();
}
}
public function updateInDatabase($table, $updateData, $conditionData)
{
if( !is_array($updateData) || !is_array($conditionData) ) {
return $this->msg_invalid_array;
}
if( !$this->validateTable($table) ) {
return $this->msg_no_table;
}
if( $this->db->update($table, $updateData, $conditionData) )
return $this->db->affected_rows();
else
return false;
}
public function deleteFromDatabase($table, $conditionData)
{
if( !is_array($conditionData) ) {
return $this->msg_invalid_data;
}
if( !$this->validateTable($table) ) {
return $this->msg_no_table;
}
return $this->db->delete($table, $conditionData);
}
public function insertOnDuplicateKeyUpdate($table, $tableData)
{
if( !is_array($tableData) ) {
return $this->msg_invalid_data;
}
if( !$this->validateTable($table) ) {
return $this->msg_no_table;
}
foreach( $tableData as $column => $value )
{
$columnNames[] = $column;
$insertValues[] = "'".$value."'";
$updateValues[] = $column." = '".$value."'";
}
$this->db->query("insert into $table(".implode(', ', $columnNames).") values(".implode(', ', $insertValues).") on duplicate key update ".implode(', ', $updateValues));
return $this->db->insert_id();
}
private function validateTable($tableName)
{
$result = $this->db->list_tables();
foreach( $result as $row ) {
if( $row == $tableName ) return true;
}
return false;
}
}