Codeigniter Model


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php if (!defined('BASEPATH')) exit('No direct script access allowed.');
  2.  
  3. class News_model extends Model {
  4. function News_model(){
  5. parent::Model();
  6.  
  7. $this->fields = explode(',', 'post_id,main_id,title,body,post_date');
  8. $this->table = 'news';
  9. $this->key = 'post_id';
  10. $this->order = 'post_date desc';
  11.  
  12. $this->reset();
  13. }
  14.  
  15. function reset(){
  16. foreach($this->fields as $field){
  17. $this->$field = null;
  18. }
  19. }
  20.  
  21. function select(){
  22. $result = false;
  23.  
  24. foreach($this->fields as $field){
  25. if($this->$field){
  26. $this->db->where($field, $this->$field);
  27. }
  28. }
  29.  
  30. $this->db->order_by($this->order);
  31. $query = $this->db->get($this->table);
  32.  
  33. if($this->post_id){
  34. $result = $query->row();
  35. } else{
  36. $result = $query->result();
  37. }
  38.  
  39. return $result;
  40. }
  41.  
  42. function update(){
  43. $result = false;
  44.  
  45. foreach($this->fields as $field){
  46. $entry[$field] = $this->$field;
  47. }
  48.  
  49. if($this->post_id){
  50. $this->db->where($this->key, $this->post_id);
  51. $this->db->update($this->table, $entry);
  52. } else{
  53. $this->db->insert($this->table, $entry);
  54. }
  55.  
  56. return $result;
  57. }
  58.  
  59. function insert(){
  60. return $this->update();
  61. }
  62.  
  63. function delete(){
  64. if($this->post_id){
  65. $this->db->where($this->key, $this->post_id);
  66. $this->db->delete($this->table);
  67. }
  68. }
  69. }
  70. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.