Showing posts with label inline crud. Show all posts
Showing posts with label inline crud. Show all posts

Thursday, 16 August 2018

Live Table Add Edit Delete using PHP with jsGrid Plugin



Live Inline CRUD operation of Create, Read, Update and Delete within a area of grid view. Live inline CRUD will add feature like adding new data and make changes in existing data dynamically using jquery with Ajax. Now here is one question how can we perform this all things, for this here we have use jsGrid jquery plugin which is lightweight jQuery grid plugin in which we can perform all CRUD operation like insert update delete and Read data using Ajax with PHP and Mysql database.

In our some previous tutorial we have discuss this things but in that we have do every things manually and we have converted table data field into editable by using contenteditable attribute and in that tutorial we have only use textbox field only but here by using jsGrid plugin we can also use most of all html input field.

jsGrid is a very popular lightweight jquery grid plugin and it is especially design for add edit delete inline mysql table data using Ajax and it is compatible with all programming language because it has use json data for sending and receiving. So, here we have use this plugin with PHP script and make simple inline insert update delete mysql data using Ajax. This tutorial will help us to add, edit and delete records into grid using PHP and Mysql. This plugin has use Ajax request for add, edit and delete data using PHP with mysql. jsGrid is a simple and very lightweight client side data grid plugin based on jQuery and by using this plugin we can perform all operation like insert new records, filter existing records, edit existing records, delete records, pagination of data and sorting of data. By using this plugin in short code you can perform very big task.

In below step by step source code you can find how can we integrate jsGrid plugin with PHP system and How can we fetch data from Mysql database and load into jsGrid plugin. How can we add or insert new records into Mysql by using jsGrid plugin with PHP. How can we edit existing mysql data by using jsGrid with PHP. How can we delete single mysql records in jsGrid using PHP. And lastly how can we make single page inline table add edit delete PHP application using this jsGrid plugin.











Source Code



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `sample_data`
--

CREATE TABLE `sample_data` (
  `id` int(10) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `age` int(3) NOT NULL,
  `gender` enum('male','female') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `sample_data`
--

INSERT INTO `sample_data` (`id`, `first_name`, `last_name`, `age`, `gender`) VALUES
(3, 'Tiny', 'Marry', 19, 'female'),
(4, 'Dolores', 'Brooks', 29, 'female'),
(5, 'Cindy', 'Dahl', 24, 'female'),
(6, 'George', 'Fagan', 30, 'male'),
(7, 'Chelsea', 'Mendoza', 18, 'female'),
(8, 'Wayne', 'Hodges', 27, 'male'),
(9, 'Keith', 'Watkin', 26, 'male'),
(10, 'Eric', 'Smith', 31, 'male'),
(11, 'Robert', 'Owens', 42, 'male'),
(12, 'Candace', 'Hand', 27, 'female'),
(13, 'Hortencia', 'Bell', 30, 'female'),
(14, 'William', 'Sosa', 36, 'male'),
(15, 'Patricia', 'Davis', 23, 'female'),
(17, 'Nancy', 'Sedlacek', 21, 'female');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `sample_data`
--
ALTER TABLE `sample_data`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_data`
--
ALTER TABLE `sample_data`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;


index.php



<html>  
    <head>  
        <title>Inline Table Insert Update Delete in PHP using jsGrid</title>  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
  <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
  <style>
  .hide
  {
     display:none;
  }
  </style>
    </head>  
    <body>  
        <div class="container">  
   <br />
   <div class="table-responsive">  
    <h3 align="center">Inline Table Insert Update Delete in PHP using jsGrid</h3><br />
    <div id="grid_table"></div>
   </div>  
  </div>
    </body>  
</html>  
<script>
 
    $('#grid_table').jsGrid({

     width: "100%",
     height: "600px",

     filtering: true,
     inserting:true,
     editing: true,
     sorting: true,
     paging: true,
     autoload: true,
     pageSize: 10,
     pageButtonCount: 5,
     deleteConfirm: "Do you really want to delete data?",

     controller: {
      loadData: function(filter){
       return $.ajax({
        type: "GET",
        url: "fetch_data.php",
        data: filter
       });
      },
      insertItem: function(item){
       return $.ajax({
        type: "POST",
        url: "fetch_data.php",
        data:item
       });
      },
      updateItem: function(item){
       return $.ajax({
        type: "PUT",
        url: "fetch_data.php",
        data: item
       });
      },
      deleteItem: function(item){
       return $.ajax({
        type: "DELETE",
        url: "fetch_data.php",
        data: item
       });
      },
     },

     fields: [
      {
       name: "id",
    type: "hidden",
    css: 'hide'
      },
      {
       name: "first_name", 
    type: "text", 
    width: 150, 
    validate: "required"
      },
      {
       name: "last_name", 
    type: "text", 
    width: 150, 
    validate: "required"
      },
      {
       name: "age", 
    type: "text", 
    width: 50, 
    validate: function(value)
    {
     if(value > 0)
     {
      return true;
     }
    }
      },
      {
       name: "gender", 
    type: "select", 
    items: [
     { Name: "", Id: '' },
     { Name: "Male", Id: 'male' },
     { Name: "Female", Id: 'female' }
    ], 
    valueField: "Id", 
    textField: "Name", 
    validate: "required"
      },
      {
       type: "control"
      }
     ]

    });

</script>



<?php

//fetch_data.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

$method = $_SERVER['REQUEST_METHOD'];

if($method == 'GET')
{
 $data = array(
  ':first_name'   => "%" . $_GET['first_name'] . "%",
  ':last_name'   => "%" . $_GET['last_name'] . "%",
  ':age'     => "%" . $_GET['age'] . "%",
  ':gender'    => "%" . $_GET['gender'] . "%"
 );
 $query = "SELECT * FROM sample_data WHERE first_name LIKE :first_name AND last_name LIKE :last_name AND age LIKE :age AND gender LIKE :gender ORDER BY id DESC";

 $statement = $connect->prepare($query);
 $statement->execute($data);
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output[] = array(
   'id'    => $row['id'],   
   'first_name'  => $row['first_name'],
   'last_name'   => $row['last_name'],
   'age'    => $row['age'],
   'gender'   => $row['gender']
  );
 }
 header("Content-Type: application/json");
 echo json_encode($output);
}

if($method == "POST")
{
 $data = array(
  ':first_name'  => $_POST['first_name'],
  ':last_name'  => $_POST["last_name"],
  ':age'    => $_POST["age"],
  ':gender'   => $_POST["gender"]
 );

 $query = "INSERT INTO sample_data (first_name, last_name, age, gender) VALUES (:first_name, :last_name, :age, :gender)";
 $statement = $connect->prepare($query);
 $statement->execute($data);
}

if($method == 'PUT')
{
 parse_str(file_get_contents("php://input"), $_PUT);
 $data = array(
  ':id'   => $_PUT['id'],
  ':first_name' => $_PUT['first_name'],
  ':last_name' => $_PUT['last_name'],
  ':age'   => $_PUT['age'],
  ':gender'  => $_PUT['gender']
 );
 $query = "
 UPDATE sample_data 
 SET first_name = :first_name, 
 last_name = :last_name, 
 age = :age, 
 gender = :gender 
 WHERE id = :id
 ";
 $statement = $connect->prepare($query);
 $statement->execute($data);
}

if($method == "DELETE")
{
 parse_str(file_get_contents("php://input"), $_DELETE);
 $query = "DELETE FROM sample_data WHERE id = '".$_DELETE["id"]."'";
 $statement = $connect->prepare($query);
 $statement->execute();
}

?>

Saturday, 30 June 2018

AngularJS Inline CRUD with PHP

Inline CRUD means perform Create, Read, Update and Delete records operation withing table grid. Inline Add, Edit and remove data operation we will be done by using AngularJS with PHP Mysql. In some of our post in which we have already discuss insert update delete mysql data by using Jquery Ajax with PHP. But now we want to make this by using AngularJS script. Live Inline CRUD has enrich web page in which we can add new records dynamically, edit or update existing data and delete or remove mysql records dynamically display remaining data on web page without refresh of web page by using AngularJS with PHP Mysql.

Fetch Data from Mysql and Display on Webpage using AngularJS with PHP




In Live Table CRUD operation first we want to fetch data from mysql table by using PHP with AngularJS and then after we want to display on webpage in tabular grid format with edit and delete button. For display data in table format we have ng-repeat directive of AngularJS. Here we can't use HTML5 contenteditable attribute because AngularJS not support this attribute. For this here when we have click on edit button then particular table row data must be converted into textbox format and edit and delete button converted into Save and cancel button. For this things we can do in AngularJS by using ng-template directive. By using this directive we can make dynamic html template for different purpose if we want to see only data then it will display in plain text format and if we want to edit data then it must be converted into textbox format. This feature we can make by using ng-template directive and by using ng-include directive we can set which template must be use in which event. So, this way we can fetch data from mysql table and load on web page in table format by using AngularJS with PHP.

Inline Table Insert or Add Data into Mysql using AngularJS with PHP




Inline Insert or Add data into Mysql means we have not to navigate form to some url and insert data and submit form and after submit page redirect to all data table page. But in table we will insert data into Mysql database by using AngularJS with PHP. For Inline table insert we will add blank table row with textbox field in start of table with Add button. So for insert data we have to fill data into inline table textbox field and click on submit button. After click on submit button data will be inserted or added into mysql table and display latest data on web page in tabular grid format without refresh of whole web page. But before inserting of data we want to validate user has filled data into textbox or not. For form validation we have to write some javascript code to validate if we have use Jquery but here we have use AngularJS. So for user has enter some data or not we have use AngularJS ng-required and ng-disabled directive. ng-required directive do some as HTML required attribute has do but it has not display any validation message on web page. But we have use ng-disabled directive on submit button then if we have not filled ng-required directive html field then this button will be disabled. But if user has filled all records then only it will enabled submit button. So this form validation we can perform by using this AngularJS ng-required and ng-disabled directive. Once user has filled form and click on Add button then data will be posted to PHP script and by using PHP script it will insert or add data into mysql table. So this way we can inline insert or add data into mysql database using PHP with AngularJS.

Inline Table Edit or Update Mysql Data using AngularJS with PHP




Inline editing or updating of Mysql data will create user simple action by allowing for edit or update grid tabular data in table itself without navigating page to other page for edit form field but we can dot edit or update of data operation on table grid. As we know we have not use contenteditable attribute of HTML, so how can we edit table data field. For editing purpose we have use ng-template directive of AngularJS. By using this directive we will convert plain text data of table data field into textbox field. So we can easily edit data. We can select dynamic template by using ng-include directive. By using this directive we can use dynamic template as per requirement. So by using this both directive of AngularJS when we have click on edit button then it will converted particular row data in editable textbox field with save and cancle button. So when we have click on edit button then that row data has been to php script for edit or update data. For send data from inline table to php script we have use ng-model directive of AngularJS. So this way we have perform inline edit or update of mysql table data by using AngularJS with PHP.

Inline Delete or remove mysql data using AngularJS with PHP




This is last operation of Inline CRUD by using AngularJS with PHP and in this we will see how can we delete or remove data from live table by using AngularJS with PHP. This is very process, for this we have to make single AngularJS function which will be executed when we have click on delete button of any particular row of data. When we have click on delete button then it will send request to PHP script delete data operation from Mysql Database. Once data has been remove then on webpage it will display remaining data on web page in tabular grid format.

So, this are the simple process of creating single page inline CRUD application by using AngularJS with PHP. In this application we can Create, Read, Update and Delete mysql data operation on single page without going to another page and all this operation will be perform without refresh of web page. Below you can find complete source of this AngularJS Inline Crud Application with PHP Mysql.


AngularJS Inline CRUD with PHP







Source Code


database_connection.php



<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

?>


index.php



<html>  
    <head>  
        <title>Inline Table Add Edit Delete using AngularJS in PHP Mysql</title>  
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>  
    </head>  
    <body>  
        <div class="container">  
   <br />
            <h3 align="center">Inline Table Add Edit Delete using AngularJS in PHP Mysql</h3><br />
   <div class="table-responsive" ng-app="liveApp" ng-controller="liveController" ng-init="fetchData()">
                <div class="alert alert-success alert-dismissible" ng-show="success" >
                    <a href="#" class="close" data-dismiss="alert" ng-click="closeMsg()" aria-label="close">&times;</a>
                    {{successMessage}}
                </div>
                <form name="testform" ng-submit="insertData()">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="text" ng-model="addData.first_name" class="form-control" placeholder="Enter First Name" ng-required="true" /></td>
                                <td><input type="text" ng-model="addData.last_name" class="form-control" placeholder="Enter Last Name" ng-required="true" /></td>
                                <td><button type="submit" class="btn btn-success btn-sm" ng-disabled="testform.$invalid">Add</button></td>
                            </tr>
                            <tr ng-repeat="data in namesData" ng-include="getTemplate(data)">
                            </tr>
                            
                        </tbody>
                    </table>
                </form>
                <script type="text/ng-template" id="display">
                    <td>{{data.first_name}}</td>
                    <td>{{data.last_name}}</td>
                    <td>
                        <button type="button" class="btn btn-primary btn-sm" ng-click="showEdit(data)">Edit</button>
                        <button type="button" class="btn btn-danger btn-sm" ng-click="deleteData(data.id)">Delete</button>
                    </td>
                </script>
                <script type="text/ng-template" id="edit">
                    <td><input type="text" ng-model="formData.first_name" class="form-control"  /></td>
                    <td><input type="text" ng-model="formData.last_name" class="form-control" /></td>
                    <td>
                        <input type="hidden" ng-model="formData.data.id" />
                        <button type="button" class="btn btn-info btn-sm" ng-click="editData()">Save</button>
                        <button type="button" class="btn btn-default btn-sm" ng-click="reset()">Cancel</button>
                    </td>
                </script>         
   </div>  
  </div>
    </body>  
</html>  
<script>
var app = angular.module('liveApp', []);

app.controller('liveController', function($scope, $http){

    $scope.formData = {};
    $scope.addData = {};
    $scope.success = false;

    $scope.getTemplate = function(data){
        if (data.id === $scope.formData.id)
        {
            return 'edit';
        }
        else
        {
            return 'display';
        }
    };

    $scope.fetchData = function(){
        $http.get('select.php').success(function(data){
            $scope.namesData = data;
        });
    };

    $scope.insertData = function(){
        $http({
            method:"POST",
            url:"insert.php",
            data:$scope.addData,
        }).success(function(data){
            $scope.success = true;
            $scope.successMessage = data.message;
            $scope.fetchData();
            $scope.addData = {};
        });
    };

    $scope.showEdit = function(data) {
        $scope.formData = angular.copy(data);
    };

    $scope.editData = function(){
        $http({
            method:"POST",
            url:"edit.php",
            data:$scope.formData,
        }).success(function(data){
            $scope.success = true;
            $scope.successMessage = data.message;
            $scope.fetchData();
            $scope.formData = {};
        });
    };

    $scope.reset = function(){
        $scope.formData = {};
    };

    $scope.closeMsg = function(){
        $scope.success = false;
    };

    $scope.deleteData = function(id){
        if(confirm("Are you sure you want to remove it?"))
        {
            $http({
                method:"POST",
                url:"delete.php",
                data:{'id':id}
            }).success(function(data){
                $scope.success = true;
                $scope.successMessage = data.message;
                $scope.fetchData();
            }); 
        }
    };

});

</script>


select.php



<?php  

//select.php
 
include('database_connection.php');

$query = "SELECT * FROM tbl_sample ORDER BY id DESC";
$statement = $connect->prepare($query);
if($statement->execute())
{
  while($row = $statement->fetch(PDO::FETCH_ASSOC))
  {
    $data[] = $row;
  }
  echo json_encode($data);
}

?>


insert.php



<?php  

//insert.php

include('database_connection.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$data = array(
 ':first_name'  => $form_data->first_name,
 ':last_name'  => $form_data->last_name
);

$query = "
 INSERT INTO tbl_sample 
 (first_name, last_name) VALUES 
 (:first_name, :last_name)
";

$statement = $connect->prepare($query);

if($statement->execute($data))
{
 $message = 'Data Inserted';
}

$output = array(
 'message' => $message
);

echo json_encode($output);

?>


edit.php



<?php  

//edit.php

include('database_connection.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$data = array(
 ':first_name'  => $form_data->first_name,
 ':last_name'  => $form_data->last_name,
 ':id'    => $form_data->id
);

$query = "
 UPDATE tbl_sample 
 SET first_name = :first_name, last_name = :last_name 
 WHERE id = :id
";

$statement = $connect->prepare($query);
if($statement->execute($data))
{
 $message = 'Data Edited';
}

$output = array(
 'message' => $message
);

echo json_encode($output);

?>


delete.php



<?php

//delete.php

include('database_connection.php');

$message = '';

$form_data = json_decode(file_get_contents("php://input"));

$query = "DELETE FROM tbl_sample WHERE id = '".$form_data->id."'";

$statement = $connect->prepare($query);
if($statement->execute())
{
 $message = 'Data Deleted';
}

$output = array(
 'message' => $message
);

echo json_encode($output);

?>