douwen1929 2016-09-15 05:15
浏览 42
已采纳

用最简单的例子在codeigniter中插入数据并简要解释MVC [关闭]

This is my model.But dont know how to insert data in database.Actually i am new to codeigniter please tell me some simple example of data insertion, maybe of form data insertion.

<?php        
class News_model extends CI_Model {            
        public function __construct(){         
                $this->load->database();                
        }                                            
        public function get_news($slug = FALSE){                
        if ($slug === FALSE){                        
                $query = $this->db->get('news');                 
                return $query->result_array();                         
        }                                             
        $query = $this->db->get_where('news', array('slug' => $slug));                   
        return $query->row_array();                
}                  
public function view($slug = NULL){    
        $data['news_item'] = $this->news_model->get_news($slug);    
        if (empty($data['news_item'])){    
                show_404();    
        }    

        $data['title'] = $data['news_item']['title'];    
        $this->load->view('templates/header', $data);    
        $this->load->view('news/view', $data);`enter code here`    
        $this->load->view('templates/footer');    
}
}
  • 写回答

1条回答 默认 最新

  • dptiq46022 2016-09-15 05:22
    关注

    Simple example would be,

    $data['title']    = $_POST['title'];
    $data['content']  = $_POST['content'];
    $data['date']     = time();
    $this->db->insert('news', $data);
    

    Note: You collect data to $data variable and insert them to news table.

    Please read more about CodeIgniter models

    PS: I see you have some miss understanding on MVC by looking at your code. Read more on that. Basically Model is used to get, insert and update data into a table. (a table == model). The best place to make a call to your view is from the controller. We call the model from the Controller -> Get values from model -> Controller receives the data -> Controller pass them to specific view. Controller handles the logic. Model does not know any logic OR to what view he should pass the data.

    There are good tutorials about CodeIgniter in youtube as well. They also explains the MVC.

    Good Luck

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?