Saturday, 19 May 2018

AngularJS PHP CRUD (Create, Read, Update, Delete) using Bootstrap Modal


In one our tutorial we have seen Crud Operation by using PHP PDO with Ajax, Bootstrap and Jquery Datatables plugin. Same way here we have make another web development tutorial on Crud operation and here we have done Crud Operation by using AngularJS with PHP, Bootstrap modal and JQuery Datatables plugin. If you have use JQuery javascript library as front-end client side development, then at that time you can follow CRUD Operation tutorial in which we have use Ajax JQuery with PHP PDO, Bootstrap modal, Jquery Datatables plugin. But on othere end there are many web developers who has use AngularJS javascript library for his front end web development. So this tutorial is for those web developer who has AngularJS instead of Jquery and in this post we have discuss how can we do insert, update, delete data operation of Mysql data by using AngularJS with PHP.

AngularJS is a Object Oriented front end or client side web development framework which has been completely written in pure JavaScript and by using AngularJS we can easy way to develop single page web applications.

Tutorial Overview


  • List all data in Jquery Datatables plugin using AngularJS
  • Add or Insert new Data in Mysql using AngularJS with PHP & Bootstrap Modal
  • Read Data from Mysql Database using AngularJS with PHP
  • Edit or Update existing Mysql data using PHP with AngularJS
  • Delete Mysql table data using AngularJS with PHP






For How to use AngularJS with PHP for Crud Operation, here we have make simple single page application for Insert, Update and Delete first name and last name mysql table data by using AngularJS with PHP & Bootstrap modal. Now Lets Step by Step develop AngularJS PHP Crud Application.

Step 1 - Make Database & Connection with Application


Here First we have make simple tbl_sample table in database and then after make database connection with PHP AngularJS Application.


--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_sample`
--

CREATE TABLE `tbl_sample` (
  `id` int(11) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

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

--
-- AUTO_INCREMENT for table `tbl_sample`
--
ALTER TABLE `tbl_sample`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

After making table in Mysql database by writing following code in database_connection.php we can make mysql database connection with AngularJS PHP application.


<?php

//database_connection.php

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



?>


Step 2 - File Structure of AngularJS PHP Crud Application


Below you can find quick overview of Files which we have use for make AngularJS PHP Crud application. Following all files are required for make this application.

  • b>angular-php-crud-application
  • angular-datatables.min.js (This is AngularJS JavaScript library)
  • bootstrap.min.css (This is Bootstrap Stylesheet library)
  • bootstrap.min.js (This is Bootstrap Javascript library)
  • database_connection.php (PHP file for Database connection)
  • datatables.bootstrap.css (This is Datatables Bootstrap style sheet library)
  • fetch_data.php (This PHP file for Select All data from Mysql Database)
  • index.html (This is Root page of our AngularJS Crud Application)
  • insert.php (This file for Insert, Update & Delete data Operation)
  • jquery.dataTables.min.css (This is Jquery Datatables stylesheet library)
  • jquery.dataTables.min.js (This is JQuery Datatables Javascript library)
  • jquery.min.js (This Jquery JavaScript library)

Step 3 - Set up Index page


Now we have proceed for develop AngularJS PHP Crud application. So, in this first we want to set up index page for this application. In index page first we want to import above javascript and css file in our index page. In index page header we have to write following html code for import javascript and css file.



<!DOCTYPE html>
<html>
 <head>
  <title>AngularJS PHP CRUD (Create, Read, Update, Delete) using Bootstrap Modal</title>
  <script src="jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="jquery.dataTables.min.js"></script>
  <script src="angular-datatables.min.js"></script>
  <script src="bootstrap.min.js"></script>
  <link rel="stylesheet" href="bootstrap.min.css">
  <link rel="stylesheet" href="datatables.bootstrap.css">
 </head>
        <body ng-app="crudApp" ng-controller="crudController">
        </body>
</html>



Here in body tag we can see two ng-app and ng-controller directive of AngularJS. By using ng-app directive we have define app name and by using ng-controller directive we have add controller to our application.

Step 4 - Load Mysql Data into Jquery Datatables using AngularJS with PHP


For make CRUD application first we want to List all mysql database data on web page. Here we have use Jquery Datatables plugin for display Mysql table data in grid format. By using this we can easily search and sort data. We have use use AngularJS with PHP for server side processing and load data into Jquery Datatables plugin. For this first we have one table in our index.html.


                         <div class="table-responsive" style="overflow-x: unset;">
    <table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>First Name</th>
       <th>Last Name</th>
      </tr>
     </thead>
     <tbody>
      <tr ng-repeat="name in namesData">
       <td>{{name.first_name}}</td>
       <td>{{name.last_name}}</td>
      </tr>
     </tbody>
    </table>
   </div>


In above HTML table code we can see some angular datatables module like datatable and dt-options for Jquery Datatables. After this we have to write following Angular Javascript code for register module and create controller.


var app = angular.module('crudApp', ['datatables']);

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


After this we have make one AngularJS function which send request to fetch_data.php page for select all data from tbl_sample mysql table and display under Jquery table tables plugin by using this ng-repeat directive.


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


This function has store data in $scope.namesData object and from this object we can display data under table by using ng-repeat directive which we can find under html table defination. This function has send request to php file and in PHP file we have to write following serverside code for fetch all data from mysql table and send to AngularJS fetchData function.


<?php

//fetch_data.php

include('database_connection.php');

$query = "SELECT * FROM tbl_sample ORDER BY id";

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

if($statement->execute())
{
 while($row = $statement->fetch(PDO::FETCH_ASSOC))
 {
  $data[] = $row;
 }

 echo json_encode($data);
}

?>


This PHP Server script will fetch all data from Mysql table and send back to AngularJS function in JSON string format by using json_encode() function. This is process for display data under JQuery Datatables plugin by using AngularJS with PHP.

Step 5 - Insert or Add data in Mysql using AngularJS with PHP & Bootstrap Modal


Now we have start discussing How can we use Bootstrap Modal with AngularJS for Insert or Add data into Mysql table by using PHP. So first on index.html page first we have write following Bootstrap alert code for display success message on web page.


                       <div class="alert alert-success alert-dismissible" ng-show="success" >
    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
    {{successMessage}}
   </div>


This html code will help us to display alert message on web page. In this we have use ng-show directive, this directive will help us to show and hide HTML element on web page. And in this we have write successMessage under double bracket, value of this will be display from model.

After this we have to write HTML code for Bootstrap modal. Because we in modal we will make form for insert or update existing data. So we have to make form in Bootstrap modal. For this we have to write following code.


<div class="modal fade" tabindex="-1" role="dialog" id="crudmodal">
 <div class="modal-dialog" role="document">
     <div class="modal-content">
      <form method="post" ng-submit="submitForm()">
         <div class="modal-header">
           <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
           <h4 class="modal-title">{{modalTitle}}</h4>
         </div>
         <div class="modal-body">
          <div class="alert alert-danger alert-dismissible" ng-show="error" >
      <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
      {{errorMessage}}
     </div>
          <div class="form-group">
      <label>Enter First Name</label>
      <input type="text" name="first_name" ng-model="first_name" class="form-control" />
     </div>
     <div class="form-group">
      <label>Enter Last Name</label>
      <input type="text" name="last_name" ng-model="last_name" class="form-control" />
     </div>
         </div>
         <div class="modal-footer">
          <input type="hidden" name="hidden_id" value="{{hidden_id}}" />
          <input type="submit" name="submit" id="submit" class="btn btn-info" value="{{submit_button}}" />
           <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
         </form>
     </div>
   </div>
</div>


Let us understand this bootstrap modal code, here we have use Bootstrap modal for form operation. Under form defination we have use ng-submit directive and in that we have define submitFrom() function. By using this directive when form data has been submitted then it will called this submitForm() function for submit form data to PHP script.

Under Bootstrap body tag we have again use Bootstrap alert code display validation error. In this code we have also use ng-show directive for hide and show HTML element on modal.

Here modal title data has been bind from Angular model. So here modal title text will be dynamic and it will be change on different operation.

For fetching form data, so here we have use ng-model directive, by using this directive we can fetch html element data in AngularJS.

Lastly, in Bootstrap modal here hidden tag and submit button value will be define by using Data binding method.


        $scope.success = false;
 $scope.error = false;


This code will hide alert success and error message html code from web page when it has been load into browser. After this we have to make AngularJS function for open and close Bootstrap modal. For this we have to write following javascript code.


       $scope.openModal = function(){
  var modal_popup = angular.element('#crudmodal');
  modal_popup.modal('show');
 };

 $scope.closeModal = function(){
  var modal_popup = angular.element('#crudmodal');
  modal_popup.modal('hide');
 };


After this we have to make one Add button in our HTML code, so we have to write following code


                       <div align="right">
    <button type="button" name="add_button" ng-click="addData()" class="btn btn-success">Add</button>
   </div>


In button tag we have use ng-click directive and here we have define one addData() function, so when we have click on this button then it will execute addData() function. So, we have write following code for addData() function.


       $scope.addData = function(){
  $scope.modalTitle = 'Add Data';
  $scope.submit_button = 'Insert';
  $scope.openModal();
 };


Now have to make submitForm() function which will be called when form has been submitted. In this function we have send request to insert.php page with form data has been pass with request. This function will be use for insert and update existing data also. In boh operation it will use this function.


           $scope.submitForm = function(){
  $http({
   method:"POST",
   url:"insert.php",
   data:{'first_name':$scope.first_name, 'last_name':$scope.last_name, 'action':$scope.submit_button, 'id':$scope.hidden_id}
  }).success(function(data){
   if(data.error != '')
   {
    $scope.success = false;
    $scope.error = true;
    $scope.errorMessage = data.error;
   }
   else
   {
    $scope.success = true;
    $scope.error = false;
    $scope.successMessage = data.message;
    $scope.form_data = {};
    $scope.closeModal();
    $scope.fetchData();
   }
  });
 };


This function has send request to insert.php server script. So, below you can find PHP script for insert data into mysql table using AngularJS with PHP. In this file we have use file_get_contents() function for received data from AngularJS function which we has been in JSON string format. So by using json_decode() we have convert into PHP array format. In this code we have also write some server side validation code also. When data has been successfully inserted then this code has send respond to AngularJS function in JSON string format by using json_encode() function.


<?php

//insert.php

include('database_connection.php');

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

$error = '';
$message = '';
$validation_error = '';
$first_name = '';
$last_name = '';

if(empty($form_data->first_name))
{
 $error[] = 'First Name is Required';
}
else
{
 $first_name = $form_data->first_name;
}

if(empty($form_data->last_name))
{
 $error[] = 'Last Name is Required';
}
else
{
 $last_name = $form_data->last_name;
}

if(empty($error))
{
 if($form_data->action == 'Insert')
 {
  $data = array(
   ':first_name'  => $first_name,
   ':last_name'  => $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';
  }
 }
 else
 {
  $validation_error = implode(", ", $error);
 }

 $output = array(
  'error'  => $validation_error,
  'message' => $message
 );

echo json_encode($output);

?>


Step 6 - Edit or Update Mysql Data using AngularJS with PHP & Bootstrap Modal


After completing step by step process for insert or add data. Now we have to move for discussing how to Edit or Update existing data of Mysql table by using AngularJS with PHP and Bootstrap modal. We have already write Bootstrap modal code, so now we do not want to make new modal we will use existing Bootstrap modal for edit data. First we have write fetchSingleData() function. This function will fetch particular data based on value of id argument. Below you can find this AngularJS function code.


            $scope.fetchSingleData = function(id){
  $http({
   method:"POST",
   url:"insert.php",
   data:{'id':id, 'action':'fetch_single_data'}
  }).success(function(data){
   $scope.first_name = data.first_name;
   $scope.last_name = data.last_name;
   $scope.hidden_id = id;
   $scope.modalTitle = 'Edit Data';
   $scope.submit_button = 'Edit';
   $scope.openModal();
  });
 };


This function has send request to insert.php file for fetch data of particular row data based on value of id argument. After successfully received of data this function has assign value to respective form field. This function also set value of hidden tag hidden id, modal title and submit button text also. Under this function lastly we have called openModal() function which will pop Bootstrap modal by using AngularJS.


<div class="table-responsive" style="overflow-x: unset;">
    <table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Edit</th>
      </tr>
     </thead>
     <tbody>
      <tr ng-repeat="name in namesData">
       <td>{{name.first_name}}</td>
       <td>{{name.last_name}}</td>
       <td><button type="button" ng-click="fetchSingleData(name.id)" class="btn btn-warning btn-xs">Edit</button></td>
      </tr>
     </tbody>
    </table>
   </div>


Here we have add one more column in table for display Edit button in each row. In each row edit button we have add ng-click=fetchSingleData(name.id), this will generate dynamic id argument value in each row function and when we have click on edit button then it will execute fetchSingleData() function and it will fetch data based on value of id argument and it will display that data in Bootstrap modal with filled form.


if($form_data->action == 'fetch_single_data')
{
 $query = "SELECT * FROM tbl_sample WHERE id='".$form_data->id."'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output['first_name'] = $row['first_name'];
  $output['last_name'] = $row['last_name'];
 }
 echo json_encode($output);
}


This is PHP script for fetch particular row of data and here we have store data in $output variable in array form and send to AngularJS function in json string format.

In AngularJS function pop up same Bootstrap modal and form which we have use for Insert data, so here we have do not want to write any extra code for submit update data form. We have to just write PHP code for update data which can find below.


                if($form_data->action == 'Edit')
  {
   $data = array(
    ':first_name' => $first_name,
    ':last_name' => $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(
  'error'  => $validation_error,
  'message' => $message
 );
echo json_encode($output);



Step 7 - Delete or Remove Mysql Data using AngularJS with PHP


This is last CRUD operation by using AngularJS with PHP. Here we will see how can we use AngularJS for delete or remove mysql table data by using PHP. For this first we have make one deleteData() AngularJS function. This function we will be called when we have click on delete button. This function will send request PHP script for delete data based on value of id argument. Below you can find AngularJS function code and html code for add one more table column for display dynamic delete button on each row and in delete button we have write ng-click directive for called deleteData() function.


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



                         <div class="table-responsive" style="overflow-x: unset;">
    <table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th>First Name</th>
       <th>Last Name</th>
       <th>Edit</th>
       <th>Delete</th>
      </tr>
     </thead>
     <tbody>
      <tr ng-repeat="name in namesData">
       <td>{{name.first_name}}</td>
       <td>{{name.last_name}}</td>
       <td><button type="button" ng-click="fetchSingleData(name.id)" class="btn btn-warning btn-xs">Edit</button></td>
       <td><button type="button" ng-click="deleteData(name.id)" class="btn btn-danger btn-xs">Delete</button></td>
      </tr>
     </tbody>
    </table>
   </div>


Now we have write php script for delete mysql table data. Above function has send delete data request to insert.php file. This file will remove or delete particular row of data based on value of id argument.


elseif($form_data->action == 'Delete')
{
 $query = "
 DELETE FROM tbl_sample WHERE id='".$form_data->id."'
 ";
 $statement = $connect->prepare($query);
 if($statement->execute())
 {
  $output['message'] = 'Data Deleted';
 }
}

echo json_encode($output);



So, here we have discuss step by step process for make AngularJS Crud Application by using PHP with Bootstrap modal. Here first we have load all mysql table data in Jquery Datatables plugin by using AngularJS with PHP. Then after this we have discuss how to insert or add data into Mysql database by using AngularJS PHP and Bootstrap modal. After inserting of data we have seen how to update or edit mysql existing data by using AngularJS with PHP and Bootstrap modal and lastly we have seen how can we delete or remove data using PHP with angularjs. This complete single page crud application by using AngularJS, PHP and Bootstrap modal because in this we can not only insert, update or delete data into mysql database but also we can search, sort and paginate data. So, If you want to get source code of AngularJS PHP Crud Application, please click on below link.




21 comments:

  1. I'm new in PHP and MySQL. I want to make a page that the user can only see and edit his data on database. Please Help

    ReplyDelete
  2. How would you approach adding other datatypes to this model such as a Checkbox/ Dropdown menu etc.

    ReplyDelete
  3. Can you please give details of the IDE you used and the application structure

    ReplyDelete
  4. I have 13,481 rows and the page crawls. Any advice on how to manage this much data and what I can change in the your code to allow smooth processing of this? Thanks.

    ReplyDelete
  5. Hi

    Thank you for the wonderful video. I changed the index.html to index.php file and want to load it in the div tag of the home page by default and on clicking the link in nav bar it should load the index.php dynamically.

    I am able to load the index.php in home page by default by using include inside div but while using the nav bar link it loads only the html leaving the angular datatable properties
    $(document).ready(function(){
    // Set trigger and container variables
    var trigger = $('#myTopnav a'),
    container = $('#content');

    // Fire on click
    trigger.on('click', function(){
    // Set $this for re-use. Set target from data attribute
    var $this = $(this),
    target = $this.data('target');

    // Load target page into container
    container.load(target + '.php');

    // Stop normal link behavior
    return false;
    });
    });


    i have many links and shld load them dynamically. Will angular js datatables not work in jquery load

    ReplyDelete
  6. it's not working, cant edit and add, only delete works

    ReplyDelete
  7. its's not working, only works delete, when want to add or edit it prompts empty error messange on top

    ReplyDelete
  8. Hi thanks for this tutorial. It is very handy!

    Can you make a tutorial as extension to this video on how to create users with roles and then login so they can see different things?

    I'm trying to do that right now and i managed to create a table in my sql and in the app so i can add users with sha1 hashed passwords but i have problem with the login. I use angular ui.route and when i try to login i cannot see data.

    I'm trying to build an app for personal use so i can track my income and expenses. I need roles so i can separate the different income in my family and buttons

    ReplyDelete
  9. I tried to use stored procedure to update.
    It also return value OUT @wynik.
    But I don't know how to read it. Do you have any idea?
    Thank you!

    if($form_data->action == 'Edit')
    {
    $data = array(
    ':maszyna' => $maszyna,
    ':program' => $program,
    ':id' => $form_data->id
    );
    /*$query = "
    UPDATE zlecenia
    SET maszyna = :maszyna, program = :program
    WHERE id = :id
    ";*/
    $query = "CALL `UpdateZlecenia`(:id, :maszyna, :program, @wynik);";

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

    ReplyDelete
  10. I cant update my data. Can you help me?

    ReplyDelete
  11. Can you help me to update data

    ReplyDelete
  12. Como usar CHARSET corretamente no AngularJS ?

    ReplyDelete
  13. First i got no error messages when adding / editing. I found that the variable in insert.php is a string. When changed to a array the error messaging works:
    $error = array();

    Now my question: after I Edit a record, the form is submitted and the new data is again fetched. The page is reloaded, but now I am on the first page again, while I was on page 8 before saving.

    I want to stay on page 8 after saving. How can I save the current page and after fetching the data return to page 8?

    ReplyDelete
  14. J'ai un problème quand j'utilise datatables avec angularjs.
    Le souci est que lorsque je charge la page les données afficher avec angularjs ne sont pas prise en compte par datatables.

    ReplyDelete
  15. Hi is there anyway to make model refresh after clicking between edit and add?

    ReplyDelete
  16. Hey i tried to insert data but it doesn't really work, php displays this error "Notice: Trying to get property 'action' of non-object"

    ReplyDelete
  17. having trouble modifying fields, replecated the first name field and checked on mysql is correct but just get red error box on insert function

    ReplyDelete
  18. IT VERY GOOD TUTORIAL; but it possible to do that for multi-option application on that i can save information for example:pastient,consulte doctor for patient and the login.

    ReplyDelete
  19. Very good tutorial ... is there someone that can fix the code?? Validation check in form doesn't work. I can only see a red box without errorMessage inside.
    In demo it works fine. If you download the code it doesn't.

    ReplyDelete
    Replies
    1. You can change $error = ''; in insert.php to
      $error = array();

      Delete