In this example we will discuss about how to delete a record or data from MySQL database using CodeIgniter framework PHP.
The DELETE statement is used to delete records from a table:
DELETE FROM table_name
WHERE some_column = some_value
Notice : The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
The students table look like this:
id | first name | last name | Email Id | Action |
---|---|---|---|---|
1 | Divyasundar | Sahu | divyasundar@gmail.com | Delete |
2 | Hritika | Sahu | hritika@gmail.com | Delete |
3 | Milan | Jena | milanjena@gmail.com | Delete |
Now i am going to delete the id=3 record.
For delete record we use 3 file here
CREATE TABLE crud (
`id` int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
`first_name` varchar(30) NOT NULL,
`last_name` varchar(30) NOT NULL,
`email` varchar(30) NOT NULL
);
<?php
class Crud extends CI_Controller
{
public function __construct()
{
/*call CodeIgniter's default Constructor*/
parent::__construct();
/*load database libray manually*/
$this->load->database();
/*load Model*/
$this->load->model('Crud_model');
}
public function displaydata()
{
$result['data']=$this->Crud_model->display_records();
$this->load->view('display_records',$result);
}
/*Delete Record*/
public function deletedata()
{
$id=$this->input->get('id');
$response=$this->Crud_model->deleterecords($id);
if($response==true){
echo "Data deleted successfully !";
}
else{
echo "Error !";
}
}
}
?>
<?php
class Crud_model extends CI_Model
{
/*Display*/
function display_records()
{
$query=$this->db->get("crud");
return $query->result();
}
function deleterecords($id)
{
$this->db->where("id", $id);
$this->db->delete("crud");
return true;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Delete records</title>
</head>
<body>
<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($data 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 "<td><a href='deletedata?id=".$row->id."'>Delete</a></td>";
echo "</tr>";
$i++;
}
?>
</table>
</body>
</html>
Now run the program on your browser with the below URL:
http://localhost/CodeIgniter/index.php/Crud/displaydata
After delete the record the table look like this.
id | first name | last name | Email Id | Action |
---|---|---|---|---|
1 | Divyasundar | Sahu | divyasundar@gmail.com | Delete |
2 | Hritika | Sahu | hritika@gmail.com | Delete |