Thursday, 15 December 2016

PHP Ajax Crud using OOPS - Update or Edit Mysql Data



In this part we have going to learn one more operation in Crud system making by using Ajax JQuery method with Object Oriented PHP programming script. In this part we have made discussion how can we edit or update mysql database table records by using PHP Object Oriented script with Ajax method. So we can change table data without refreshing page.

In previous part we have seen Insert or Add new records in Mysql Database table by using Ajax with PHP script. In any web application or system, changing or updating or editing data are required, this is because first if we have add wrong information in any system then after we want to change that information, then we want to required update operation, So Update of data is one of the part of Crud system. In this system we have not only change data but also we will change or upload new image by using Ajax with PHP script.

In this part first we have fetch single data by using Ajax with PHP Object oriented script in json format and then after we have load that data in different form field, so after data has come into form fields so we can change value of form field and by clicking on submit button we can send form data to server with file and by using Form Data object and we have send form data to server by using Ajax method. So this way we can edit or update with upload image by using Ajax method with Object Oriented programming. In next part we will learn how to delete data by using Ajax with PHP Object Oriented Script without page refresh.




Source Code


 <?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>  
           ';  
           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>  
                ';  
           }  
           $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


 <?php  
 include 'crud.php';  
 $object = new Crud();  
 ?>  
 <html>  
      <head>  
           <title>PHP Ajax Crud using OOPS - Insert or Add 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 - Insert or Add 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);  
                     }  
                });  
           });  
      });  
 </script>  

action.php


 <?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';  
      }  
 }  
 ?>  

1 comment: