Wednesday, 14 December 2016

PHP Ajax Crud using OOPS - Insert or Add Mysql Data



In this part of Creating Crud system by using Object Oriented PHP programming with Ajax, We will learn how can we Insert or Add data into Mysql database table by using PHP Object Oriented Programming Concept with JQuery Ajax method. So We can Insert or Add data and refresh HTML table data without page refresh.

In previous part we have already fetch or select data from Mysql database table by using Object Oriented PHP script with Ajax method, but now we will see that how can we use Object and class code for Inserting data with Ajax method. Inserting of data is the one part of any Crud operation and In web development also Insert or Save of records is the one of common part, so in future we can use that records by retrieving.

In this system we will developed PHP Crud Operation without page refresh by using PHP Object Oriented Programming with Ajax Jquery and Bootstrap framework. If we use PHP Object Oriented Programming Code as back end and in Front end we have use Ajax. So this type of system will work faster than normal php scripted system. In Latest trend most of the web application use ajax for any type operation, this is because user can do any operation without going to another page.

So In this part we have seen not only how can we insert data but also upload image by using Ajax Jquery method with Object Oriented PHP programming without page refresh. For making stylish form we have use Bootstrap Collapse, by using Bootstrap Collapse we can hide form on web page, but when we want to add new data then at that time we can visible form on web page. So by using Bootstrap Collapse we can hide large amount of content on web page but here we have use for hide form. This is the unique you can also use in your web development project. So In this Crud system we have seen how can we use Bootstrap Collapse for Inserting data into Mysql database table by using Ajax Jquery method with Object Oriented PHP programming, so we can add new records without page refresh. We can also called inserting or adding live data or single page web application also. In next part we will make discussing on how to update or edit Mysql table data by using Ajax with PHP Object Oriented Programming script.



Source Code


crud.php


 <?php  
 class Crud  
 {  
      //crud class  
      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  
 //index.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" />  
                          <br />  
                          <div align="center">  
                               <input type="hidden" name="action" id="action" />  
                               <input type="submit" name="button_action" id="button_action" class="btn btn-default" value="Insert" />  
                          </div>  
                     </form>  
                </div>  
                <br /><br />  
                <div id="user_table" class="table-responsive">  
                </div>  
           </div>  
      </body>  
 </html>  
 <script type="text/javascript">  
      $(document).ready(function(){  
           load_data();  
           $('#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();  
                          }  
                     })  
                }  
                else  
                {  
                     alert("Both Fields are Required");  
                }  
           });  
      });  
 </script>  

action.php


 <?php  
 //action.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';  
      }  
 }  
 ?>  

4 comments:

  1. Sir, i have a doubt in automatic logout after 15 min . using session .. i want to know that why you redeclare $_session ['last_login_timestamp']=time () in index.php page

    ReplyDelete
  2. In automatic logout after 15 minites video.
    http://youtu.be/Wbo7ryb_xl4

    ReplyDelete
  3. If i am not redeclare this time () it will show an error
    (Undefined index )

    ReplyDelete