Update Data
How to Update Data from Database

1- Create Controller  - To run script

2- Create Model - To create view and update query

3- Then create HTML pages to display data - To display record with Edit link, To display single record

Create Controller and save in controller folder(controllers->User.php)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

public function __construct() {
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->model('user_model');
}

public function index()
{
$data['user']=$this->user_model->fetch_data();
$this->load->view('display',$data);
}

public function edit()
{
$data['records']=$this->user_model->fetch_record();
$this->load->view('edit_view',$data);
}

public function update()
{
$id = $this->uri->segment('3');
$this->user_model->update_record($id);
redirect('user/index');
}

}

Create page and save in view folder (View->display.php)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<html>
<head>
<title>Display Data</title>
</head>
<body>
<table border="1">
<tr>
<td><b>Name</b></td>
<td><b>Email</b></td>
<td><b>City</b></td>
<td><b>Action</b></td>
</tr>
<?php
foreach($user as $row){
?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->email; ?></td>
<td><?php echo $row->city; ?></td>
<td><a href="<?php echo base_url()."index.php/user/edit/".$row->id; ?>">Edit</a></td>
</tr>
<?php
}
?>
</table>
</body>
</html>

Create page and save in view folder (View->edit_view.php)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<html>
<head>
<title>Update Data</title>
</head>
<body>
<form name="frm" action="<?php echo base_url(); ?>index.php/user/update/<?php echo $records[0]->id; ?>" method="post">
Enter Name<input name="name" type="text" value="<?php echo $records[0]->name; ?>"/><br />
Enter Email<input name="email" type="text" value="<?php echo $records[0]->email; ?>"/><br />
Enter City<input name="city" type="text" value="<?php echo $records[0]->city; ?>"/><br />
<input name="btn" type="submit" value="Update"/>
</form>
</body>
</html>

Create modal and save in models folder (models->edit_view.php)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User_Model extends CI_Model {

public function fetch_data()
{
$this->db->select('*');
$q = $this->db->get('tbl_user');
return $q->result();
}

public function fetch_record(){
$id = $this->uri->segment('3');
$query = $this->db->get_where("tbl_user",array("id"=>$id));
return $query->result();
}

public function update_record($id){
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'city' => $this->input->post('city')
);
$this->db->where("id", $id);
$this->db->update("tbl_user", $data);
}

}


Previous
Next