Welcome Guest, Not a member yet? Register   Sign In
How to update a row in the database?
#1

[eluser]towki[/eluser]
I have managed to create methods for adding, viewing data in the database but for updating, I still cant figure it out.

Im confused how to retrieve the data in the row to be edited and display it in its corresponding forms just like how it was added.I still dont have a method or any codes in my MVC for this.I only know how to create the action links for updating a single row by using the ID field in that row. But i dont know how to make use of that link.

Please give me examples how do you update the data in a row, if you dont mind, i like it in complete MVC pattern and I'll try to understand. I hope you all got my point even my English is bad.

Thanks.

#2

[eluser]Egill Th[/eluser]
Here is a small example on how you could update news posts, I haven't tested it out but you should be able to work with this and alter it to suit your needs.

News.php controller
Code:
<?php
class News extends CI_Controller {
  var $data;

  public function __construct() {
    $this->load->model('newsmodel');
  }

  public function updateNewsItem($id) {
    $this->data['item'] = $this->newsmodel->getNewsItem($this->db->escape($id));

    if(isset($_POST['submit'])) {
      $this->newsmodel->updateNewsItem(
        $this->db->escape($id),
        array(
          'subject' => $this->db->escape($this->input->post('subject')),
          'body' => $this->db->escape($this->input->post('body')),
        )
      );

     redirect('news/view/' . $id . '/');
    }
    
    $this->load->view('updateNews.php', $this->data);
  }
}

Newsmodel.php model
Code:
<?php
class Newsmodel extends CI_Model {
  var $table = 'newspost';

  public function __construct() {
    parent::__construct();
  }

  public function getNewsItem($id) {
    $result = $this->db->get_where('newspost', array('id', $id));

    return $result->result();
  }

  public function updateNewsItem($id, $data) {
    $this->db->where('id', $id);
    $this->db->update('newspost', $data);
  }

updateNews.php view
Code:
<form method="post">
<input id="subject" name="subject" type="text" value="<?php echo $item[0]->subject; ?>">
<textarea id="body" name="body"><?php echo $item[0]->body; ?></textarea>
<input name="submit" type="submit" value="Submit changes">
</form>




Theme © iAndrew 2016 - Forum software by © MyBB