Posted By

michaelfox on 04/20/09


Tagged

database model ci Framework codeigniter


Versions (?)

Who likes this?

16 people have marked this snippet as a favorite

eunjoo1984
optim
vali29
nkm
KF
paschim
dantreacy
vkolev
wortell
infinidad
tamala73
Gordy
ljayz
prit
jsamackay
Priestd09


Codeigniter Model


 / Published in: PHP
 

  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
Posted By: eunjoo1984 on April 24, 2009

looks like a realy nice template

if you change the delete function like bellow you wouldn't have to touch it at all.

    function delete(){
        if($this->{$this->key}){
            $this->db->where($this->key, $this->{$this->key});
            $this->db->delete($this->table);
        }
    }
Posted By: siddheshshivtarkargmailcom on May 8, 2009

oh!!! it really helped me !!! for object oriented approach its really nice code.... just needs some changes as insert and update function can be merged. i.e. call one function if id is set then update the record or else insert the record... and if fields are given extra space it creates a problem....

thats it !!!! else the function is really nice...thanks for developing.....:)

You need to login to post a comment.