Delete Data
How to Delete Data from Database

1- Create Controller  - To run script

2- Create Model - To create delete query

3- Then create HTML page to display data - To display record with delete link

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 delete()
{
$id=$this->uri->segment(3);
$this->user_model->delete_record($id);
redirect('user/index');
}

}

Create Page and save in view folder(views->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/delete/".$row->id; ?>">Delete</a></td>
</tr>
<?php
}
?>
</table>
</body>
</html>

Create Model and save in modal folder(models->user_modal.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 delete_record($id){
$this->db->where('id', $id);
$this->db->delete('tbl_user');
}

}


Previous
Next