A set of methods to speed up your development for CodeIgniter 1.x. Update for CodeIgniter 2 is available.
system/application/libraries/MY_Model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class MY_Model extends Model { var $table = ""; function My_Model() { parent::Model(); $this->load->database(); } function insert($data) { $this->db->insert($this->table, $data); return $this->db->insert_id(); } function find_id($id) { if ($id == NULL) { return NULL; } $this->db->where('id', $id); $query = $this->db->get($this->table); $result = $query->result_array(); return (count($result) > 0 ? $result[0] : NULL); } function find_all($sort = 'id', $order = 'asc') { $this->db->order_by($sort, $order); $query = $this->db->get($this->table); return $query->result_array(); } function update($id, $data) { $this->db->where('id', $id); $this->db->update($this->table, $data); } function delete($id) { if ($id != NULL) { $this->db->where('id', $id); $this->db->delete($this->table); } } } /* End of file MY_Model.php */ /* Location: ./system/application/libraries/MY_Model.php */
system/application/models/book.php
<?php class Book extends MY_Model { function Book() { parent::MY_Model(); $this->table = 'book'; } /* End of file book.php */ /* Location: ./system/application/models/book.php */
$this->load->model('book'); $book = array(); $book['title'] = 'The Black Dahlia'; $book['author'] = 'James Ellroy'; $this->book->insert($book);
$this->load->model('book'); $book = $this->book->find_id('47'); echo $book['title'];
$this->load->model('book'); $book_list = $this->book->find_all('title', 'asc'); foreach ($book_list as book) { echo $book['title']; }
$this->load->model('book'); $this->book->delete('47');