Last active
February 2, 2018 19:44
-
-
Save steveosoule/7b0bf3df2b023de0895d to your computer and use it in GitHub Desktop.
CodeIgniter - Smart Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); | |
// FROM: http://www.thephpcode.com/blog/view/a-smart-codeigniter-model.html | |
class MY_Model extends CI_Model { | |
public $table; | |
public function __construct() | |
{ | |
parent::__construct(); | |
// $this->table = get_Class($this); | |
$this->table = preg_replace("/_model$/", '', strtolower(get_Class($this)) ); | |
var_dump($this->table); | |
$this->load->database(); | |
} | |
public function save($data,$tablename="") | |
{ | |
if($tablename=="") | |
{ | |
$tablename = $this->table; | |
} | |
$op = 'update'; | |
$keyExists = FALSE; | |
$fields = $this->db->field_data($tablename); | |
foreach ($fields as $field) | |
{ | |
if($field->primary_key==1) | |
{ | |
$keyExists = TRUE; | |
if(isset($data[$field->name])) | |
{ | |
$this->db->where($field->name, $data[$field->name]); | |
} | |
else | |
{ | |
$op = 'insert'; | |
} | |
} | |
} | |
if($keyExists && $op=='update') | |
{ | |
$this->db->set($data); | |
$this->db->update($tablename); | |
if($this->db->affected_rows()==1) | |
{ | |
return $this->db->affected_rows(); | |
} | |
} | |
$this->db->insert($tablename,$data); | |
return $this->db->affected_rows(); | |
} | |
public function search($conditions=NULL,$tablename="",$limit=500,$offset=0) | |
{ | |
if($tablename=="") | |
{ | |
$tablename = $this->table; | |
} | |
if($conditions != NULL) | |
$this->db->where($conditions); | |
$query = $this->db->get($tablename,$limit,$offset=0); | |
return $query->result(); | |
} | |
public function insert($data,$tablename="") | |
{ | |
if($tablename=="") | |
$tablename = $this->table; | |
$this->db->insert($tablename,$data); | |
return $this->db->affected_rows(); | |
} | |
public function update($data,$conditions,$tablename="") | |
{ | |
if($tablename=="") | |
$tablename = $this->table; $this->db->where($conditions); | |
$this->db->update($tablename,$data); | |
return $this->db->affected_rows(); | |
} | |
public function delete($conditions,$tablename="") | |
{ | |
if($tablename=="") | |
$tablename = $this->table; | |
$this->db->where($conditions); | |
$this->db->delete($tablename); | |
return $this->db->affected_rows(); | |
} | |
} | |
/* End of file MY_model.php */ | |
/* Location: ./application/models/MY_model.php */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment