Monday, 24 September 2012

Updating and deleting data in codeigniter

In this page iam describing about updating data in a codeigniter. Here iam explaining with the help of an example, so that you can understand it easily:-

UPDATING DATA

Usually there araise situation whereyou want to update the content added.
Generally we have to pass id of record from a record listing to a page to edit a particular record. In codeigniter we can do with built in function like this :-
 <?php echo anchor('admin/updatenews/' .$news_item['news_id'],"Update", array('title' => $ads_id = $news_item['news_id']));?>

so here id will be passed through the url:-
url wll be looking something like this:-
http://localhost/CodeIgniter/index.php/admin/updatenews/24

In codeigniter you can retrieve data like this:-
$newsid = $this->uri->segment(3);

you will get $newsid like this.


public function updatenews(){

$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$this->form_validation->set_rules('txtTitle', 'title', 'required');
$this->form_validation->set_rules('txtContent', 'content', 'required');
$data['urls']=base_url();
 $newsid = $this->uri->segment(3);
$news=$this->news_model->getnewsitem($newsid);//retreiving newsitem
$data['news']=$news;

$this->load->view('templates/headermain',$data);
$this->load->view('admin/updatenews',$data);
$this->load->view('templates/footermain',$data);
$save=$this->input->post('saveForm');
if($save){

$list=array('title'=>$title,'content'=>$content,'publish'=>$publish,'id'=>$newsid);//
$this->news_model->updatenews($list);//pasing as array to the model
redirect('admin/news',$data); 
}

so you have to write afunction in model like this :-


public function updatenews($list)

$dateup=date('Y-m-d H:i:s');
$data = array(
'published'=>$list['publish'],
'title' =>$list['title'],
'content' => $list['content'],
'date_update'=>$dateup
);

$this->db->where('news_id',$list['id']);
                   $this->db->update('news',$data); 
                   return 1;
}

and your update html view would be like:-

  <?php

$attributes=array('newsid'=>$news[0]['news_id']);
                      echo form_open_multipart('admin/updatenews',$attributes); ?>// here attributes can be passed like this




<h6>Title
                             </h6>
                          
                            <div class="row450">
                       Title:-      <input type="text" name="txtTitle"  size="40" maxlength="90" tabindex="2" value="<?php echo $news[0]['title']; ?>"  class="txtAdd_new">
                            </div>
content:-
<textarea name="txtContent" id="txtContent" rows="10" cols="40" tabindex="6"><?php echo $news[0]['content']; ?></textarea>


DELETING DATA

For deleting data you can use this function :-

 $this->db->where('news_id',$list[$i]);
                   $this->db->delete('news',$data); 





No comments:

Post a Comment