harsh sharma harsh sharma - 14 days ago 5
PHP Question

inserting data in codeigniter with simplest example and explain MVC in short

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');
}
}

Answer

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