For any queries you can reach us at infovistarindia@gmail.com / WhatsApp us: +919158876092

Delete data from Database using CodeIgniter

Introduction

The DELETE statement is used to delete records from a table:
DELETE FROM table_name
WHERE some_column = some_value

Note: The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!

Controller: 	User.php		application\controllers\User.php
Model:		User_model.php		application\models\User_model.php
View:		list.php		application\views\list.php

applications/controllers/User.php

class User extends CI_Controller {

	public function __construct() {
		/*call CodeIgniter's default Constructor*/
		parent::__construct();

		/*load model*/
		$this->load->model('User_model');
	}
	
	public function list() {
		$data[‘result’]	= $this->user_model->list();
		$this->load->view(‘list’, $data);
	}

	public function delete($id) {
		$result = $this->user_model->delete($id);
		if($result) {
			echo “User record is deleted successfully.”;
		} else {
			echo “Something went wrong”;
		}

	}
}

applications/models/User_model.php

class User_model extends CI_Model {
	/*Select*/
	function list() {
		$this->db->select([“*”]);
		$this->db->from(‘user_info’);
		$query = $this->db->get();
		return $query->result();
	}

	public function delete($id) {
		$where = [“id” => $id];
		return $this->db->delete(‘user_info’, $where);
	}
	
}

applications/views/list.php

<table width="600" border="1" cellspacing="5" cellpadding="5">
	<tr style="background:#CCC">
		<th>Sr No</th>
		<th>First_name</th>
		<th>Last_name</th>
		<th>Email Id</th>
		<th>Delete</th>
		<th>Update</th>
	</tr>
	<?php $i=1; foreach($result as $row) { 
		echo "<tr>"; 
		echo "<td>".$i. "</td>"; 
		echo "<td>".$row->first_name."</td>";
		echo "<td>".$row->last_name."</td>"; 
		echo "<td>".$row->email."</td>"; 
		echo "</tr>"; $i++; } ?>
		echo "<td><a href=”<?php echo base_url('user/delete'.$row->id) ?>”>Delete</a></td>";
</table>