[SOLVED] Give Notification When Can't Delete Primay Key Row Which is Foreign Key of Another Table

As we know, to maintain data integrity, when we delete a primary key row that is used as a foreign key in another table it will be error because it is restrict. but if the data has not been used of course it can still be deleted.


One of the ways that data can be erased is to use the ON DELETE CASCADE feature if we used phpmyadmin, where when the primary key is deleted the data that uses the primary key as a foreign key will also be deleted. But the problem is that if important data is erased, data integrity will be lacking.

So here I will give a solution where the data condition remains RESTRICT and there is a notification when the data cannot be deleted. this time I use codeigniter framework.

I have two table like this

Table 1 : Sumber
Table 2 : Barang
i want to give delete button from my view, so that the code like below :
  • Views : tampil_sumber.php (click trash button)

.....
<?php echo $this->session->flashdata('message');?>
...
<?php $onclick = array('onclick'=>"return confirm('Are you sure to delete?')");?>
                                  <?php echo anchor('sumber/sumber_delete/'.$smb->id_sumber, '<div class="btn btn-danger btn-sm"><i class="fas fa-trash"></i></div>',$onclick); ?>
...
  • Controller : sumber.php

...
public function sumber_delete($id){
$where = array('id_sumber'=>$id);
$cek = $this->model_sumber->is_ada_sumber($id);
if (count($cek)>0){
$this->session->set_flashdata('message','<div class="alert alert-danger alert dismissible fade show" role="alert">Sumber can't delete!<button type="button" class="close" data-dismiss="alert" aria=label="Close"><span aria-hidden="true">&times;</span></button></div>');
}else{
$this->model_sumber->delete_sumber($where);
$this->session->set_flashdata('pesan','<div class="alert alert-success alert dismissible fade show" role="alert">Delete Success!<button type="button" class="close" data-dismiss="alert" aria=label="Close"><span aria-hidden="true">&times;</span></button></div>');
}
redirect('sumber');
}
...

  • Model : model_sumber.php


...
public function is_ada_sumber($id){
$this->db->select('*');
$this->db->from('barang');
$this->db->where(array('id_sumber' => $id));
$query=$this->db->get();
   return $query->result();
}

public function delete_sumber($where){
$this->db->where($where);
$this->db->delete('sumber');
}
...

And it's work guys :)





Comments

Popular posts from this blog

BELAJAR DARI PENGALAMAN

[Tech Tips #1] Check Apakah Datamu Bocor, dimana?

PENDIDIKAN LUAR SEKOLAH UNTUK APA SIH?