Showing posts with label php mvc delete. Show all posts
Showing posts with label php mvc delete. Show all posts

Wednesday, 5 December 2018

PHP MVC Delete

How to Delete data in a database using PHP MVC with an example 

In this example, we using Models, Views, Controller Structure for Delete the inserted data.

To Delete data in the database first we have to create a Controller file.
controller/index.php
<?php
class Index extends Controller {
function __construct() {
parent::__construct();
}
function index() {
$this->view->allrecords = $this->model->getAllrecords();
$this->view->render('index/index');
}
function delete_index($id) 
{
$this->model->delete_index($id);
header('location: ../index/index');
}
}
Here is the model file which we are using for Delete data from database.
The file index_model.php is created under Models folder
models/index_model.php

index_model.php

<?php
class Index_Model extends Model
{
public function __construct()
{
parent::__construct();
}
public function getAllrecords()
{
return $this->db->select("SELECT * FROM `mvc` ORDER BY id DESC");
}
public function delete_index($id) 
{ $this->db->delete('mvc'"`id` = {$id}");
}
}
Here is the view file index.php which inside views folder contains the table
views/index/index.php
<table border="2" id="internalActivities" style="width:100%" class="table table-bordered">
<tr>
<th>Name</th>
<th>Email</th>
<th>contact</th>
<th></th>
</tr>
<?php foreach($this->allrecords AS $key=>$value){
?>

<tr>
<td><?php echo $value['name']."<br>"?></td>
<td><?php echo $value['email']."<br>"?></td>
<td><?php echo$value['contact'];?></a>
</td>
<td><a href="javascript:confirmDelete('delete_index/<?php echo $value['id'];?>')" class="btn btn-primary btn-sm" role="button">Delete</a></td>
<?php } ?>
</table>
<script>
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
document.location = delUrl;
}
}
</script>
Path: localhost/project_folder_name/view_folder_name/view_filename
Example: localhost/mvc/index/index