Tuesday 20 December 2016

PHP Mysql Ajax Crud using OOPS - Delete or Remove Data



If you are looking for more Web tutorial on hot topic like PHP Object Oriented Crud system by using Ajax Jquery method, In this part we will make discussion on how to remove or delete Mysql database table records or data by using Ajax with Object Oriented PHP script.

In this system we can delete data without page refresh event because in this system we have use Ajax method. In most of the web application there are Insert, Update, Delete and Fetch of data are common operation. But in this system we have use Ajax request for removing or deleting of data without going to another page.

In previous part we have already made discussing on how to update or edit of data by using Ajax method with Object Oriented PHP script and we have make one crud class in which we have make data base connection function, execution of query function, fetch data in table format function, fetching of single user data function and many more function.

So In this crud system, now we can remove or delete data by using Ajax Jqery method with Object Oriented PHP script. Here we have use Javascript confirm box for one more time asking for deleting of data. So here we can validate user action for really he want to remove data from system. For removing of data we have use Ajax request send to server and at server side we have per delete data query for removing of data. So this way we have use Ajax Request with Object Oriented PHP programming for removing or delete of data from Mysql data table. In next we will learn one more functionality of crud system like Live table data search by using Ajax JQuery method with Object Oriented PHP script.




Source Code


crud.php


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
class Crud
{
 public $connect;
 private $host = 'localhost';
 private $username = 'root';
 private $password = '';
 private $database = 'crud'; 

 function __construct()
 {
  $this->database_connect();
 }

 public function database_connect()
 {
  $this->connect = mysqli_connect($this->host, $this->username, $this->password, $this->database);
 }

 public function execute_query($query)
 {
  return mysqli_query($this->connect, $query);
 }

 public function get_data_in_table($query)
 {
  $output = '';
  $result = $this->execute_query($query);
  $output .= '
  <table class="table table-bordered table-striped">
   <tr>
    <th width="10%">Image</th>
    <th width="35%">First Name</th>
    <th width="35%">Last Name</th>
    <th width="10%">Update</th>
    <th width="10%">Delete</th>
   </tr>
  ';
  if(mysqli_num_rows($result) > 0)
  {
   while($row = mysqli_fetch_object($result))
   {
    $output .= '
    <tr>
     <td><img src="upload/'.$row->image.'" class="img-thumbnail" width="50" height="35" /></td>
     <td>'.$row->first_name.'</td>
     <td>'.$row->last_name.'</td>
     <td><button type="button" name="update" id="'.$row->id.'" class="btn btn-success btn-xs update">Update</button></td>
     <td><button type="button" name="delete" id="'.$row->id.'" class="btn btn-danger btn-xs delete">Delete</button></td>
    </tr>
    ';
   }
  }
  else
  {
   $output .= '
    <tr>
     <td colspan="5" align="center">No Data Found</td>
    </tr>
   ';
  }
  $output .= '</table>';
  return $output;
 }
 
 function upload_file($file)
 {
  if(isset($file))
  {
   $extension = explode('.', $file['name']);
   $new_name = rand() . '.' . $extension[1];
   $destination = './upload/' . $new_name;
   move_uploaded_file($file['tmp_name'], $destination);
   return $new_name;
  }
 }
}
?>

index.php


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
<?php
include 'crud.php';
$object = new Crud();
?>
<html>
 <head>
  <title>PHP Ajax Crud using OOPS - Delete or Remove Mysql Data</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
   body
   {
    margin:0;
    padding:0;
    background-color:#f1f1f1;
   }
   .box
   {
    width:1270px;
    padding:20px;
    background-color:#fff;
    border:1px solid #ccc;
    border-radius:5px;
    margin-top:10px;
   }
  </style>
 </head>
 <body>
  <div class="container box">
   <h3 align="center">PHP Ajax Crud using OOPS - Delete or Remove Mysql Data</h3><br />
   <button type="button" name="add" class="btn btn-success" data-toggle="collapse" data-target="#user_collapse">Add</button>
   <br /><br />
   <div id="user_collapse" class="collapse">
    <form method="post" id="user_form">
     <label>Enter First Name</label>
     <input type="text" name="first_name" id="first_name" class="form-control" />
     <br />
     <label>Enter Last Name</label>
     <input type="text" name="last_name" id="last_name" class="form-control" />
     <br />
     <label>Select User Image</label>
     <input type="file" name="user_image" id="user_image" />
     <input type="hidden" name="hidden_user_image" id="hidden_user_image" />
     <span id="uploaded_image"></span>
     <br />
     <div align="center">
      <input type="hidden" name="action" id="action" />
      <input type="hidden" name="user_id" id="user_id" />
      <input type="submit" name="button_action" id="button_action" class="btn btn-default" value="Insert" />
     </div>
     <br />
    </form>
   </div>
   <br />
   <div class="table-responsive" id="user_table">
    
   </div>
  </div>
 </body>
</html>

<script type="text/javascript">
 $(document).ready(function(){
  
  load_data();
  $('#action').val("Insert");
  $('#add').click(function(){
   $('#user_form')[0].reset();
   $('#uploaded_image').html('');
   $('#button_action').val("Insert");
  });
  function load_data()
  {
   var action = "Load";
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{action:action},
    success:function(data)
    {
     $('#user_table').html(data);
    }
   });
  }
  
  $('#user_form').on('submit', function(event){
   event.preventDefault();
   var firstName = $('#first_name').val();
   var lastName = $('#last_name').val();
   var extension = $('#user_image').val().split('.').pop().toLowerCase();
   if(extension != '')
   {
    if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
    {
     alert("Invalid Image File");
     $('#user_image').val('');
     return false;
    }
   }
   if(firstName != '' && lastName != '')
   {
    $.ajax({
     url:"action.php",
     method:'POST',
     data:new FormData(this),
     contentType:false,
     processData:false,
     success:function(data)
     {
      alert(data);
      $('#user_form')[0].reset();
      load_data();
      $("#action").val("Insert");
      $('#button_action').val("Insert");
      $('#uploaded_image').html('');
     }
    });
   }
   else
   {
    alert("Both Fields are Required");
   }
  });

  $(document).on('click', '.update', function(){
   var user_id = $(this).attr("id");
   var action = "Fetch Single Data";
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{user_id:user_id, action:action},
    dataType:"json",
    success:function(data)
    {
     $('.collapse').collapse("show");
     $('#first_name').val(data.first_name);
     $('#last_name').val(data.last_name);
     $('#uploaded_image').html(data.image);
     $('#hidden_user_image').val(data.user_image);
     $('#button_action').val("Edit");
     $('#action').val("Edit");
     $('#user_id').val(user_id);
    }
   });
  });
  $(document).on('click', '.delete', function(){
   var user_id = $(this).attr("id");
   var action = "Delete";
   if(confirm("Are you sure you want to delete this?"))
   {
    $.ajax({
     url:"action.php",
     method:"POST",
     data:{user_id:user_id, action:action},
     success:function(data)
     {
      alert(data);
      load_data();
     }
    });
   }
   else
   {
    return false;
   }
  });
 });
</script>

action.php


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
include 'crud.php';
$object = new Crud();
if(isset($_POST["action"]))
{
 if($_POST["action"] == "Load")
 {
  echo $object->get_data_in_table("SELECT * FROM users ORDER BY id DESC");
 }
 if($_POST["action"] == "Insert")
 {
  $first_name = mysqli_real_escape_string($object->connect, $_POST["first_name"]);
  $last_name = mysqli_real_escape_string($object->connect, $_POST["last_name"]);
  $image = $object->upload_file($_FILES["user_image"]);
  $query = "
  INSERT INTO users
  (first_name, last_name, image) 
  VALUES ('".$first_name."', '".$last_name."', '".$image."')";
  $object->execute_query($query);
  echo 'Data Inserted'; 
 }
 if($_POST["action"] == "Fetch Single Data")
 {
  $output = '';
  $query = "SELECT * FROM users WHERE id = '".$_POST["user_id"]."'";
  $result = $object->execute_query($query);
  while($row = mysqli_fetch_array($result))
  {
   $output["first_name"] = $row['first_name'];
   $output["last_name"] = $row['last_name'];
   $output["image"] = '<img src="upload/'.$row['image'].'" class="img-thumbnail" width="50" height="35" />';
   $output["user_image"] = $row['image'];
  }
  echo json_encode($output);
 }

 if($_POST["action"] == "Edit")
 {
  $image = '';
  if($_FILES["user_image"]["name"] != '')
  {
   $image = $object->upload_file($_FILES["user_image"]);
  }
  else
  {
   $image = $_POST["hidden_user_image"];
  }
  $first_name = mysqli_real_escape_string($object->connect, $_POST["first_name"]);
  $last_name = mysqli_real_escape_string($object->connect, $_POST["last_name"]);
  $query = "UPDATE users SET first_name = '".$first_name."', last_name = '".$last_name."', image = '".$image."' WHERE id = '".$_POST["user_id"]."'";
  $object->execute_query($query);
  echo 'Data Updated';
 }
 if($_POST["action"] == "Delete")
 {
  $query = "DELETE FROM users WHERE id = '".$_POST["user_id"]."'";
  $object->execute_query($query);
  echo 'Data Deleted';
 }
}
?>

6 comments:

  1. Hi, great job and tutorials. But for me do not work upadate and add buttons. Can you upload all project? im new in php, so it would help me very much. greatings from lithuania.

    ReplyDelete
  2. Undefined index : user_id

    can u help me with this?

    ReplyDelete
  3. when i click delete.. its gives a empty message buy doesn't gets deleted ?? can u help me with this?

    ReplyDelete
  4. sorry it is working good ...Thank u

    ReplyDelete
  5. where is database file ? without sql file this post is valueless for new learner.

    ReplyDelete
    Replies
    1. yeah, wheres the database file?im a new learner and im lost.
      i guess i have to force my way.

      Delete