Wednesday, January 29, 2020

AngularJS PHP CRUD (Create,Read,Update,Delete) Operations

AngularJS PHP  CRUD (Create,Read,Update,Delete) Operations

In one of our tutorials we saw that Operation Crud uses PHP PDO with the addition Ajax, Bootstrap and Jquery Datatables. In the same way we did another web development tutorial for the crud operation here and here the crud operation using AngularJS with PHP, Bootstrap-Modal and the JQuery Datatables add-on. If you've used the JQuery Javascript library as a client-side front-end development, you can follow the CRUD operation tutorial where Ajax JQuery was used with PHP PDO, Bootstrap Modal and the Jquery Datatables plugin. On the other hand, there are many web developers who have used the AngularJS JavaScript library for their front-end web development. This tutorial is aimed at those web developers who use AngularJS instead of Jquery. This post explained how to insert, update, and delete mysql data using AngularJS with PHP.

AngularJS is an object-oriented or client-side front-end web development framework written entirely in pure JavaScript. By using AngularJS we can simplify the development of one-sided web applications.


Tutorial Summary



  • List all data in the Jquery Datatables plug-in with AngularJS
  • Add or insert new data in MySQL with AngularJS with PHP and Bootstrap Modal
  • Reads data from the MySQL database using AngularJS using PHP
  • Edit or update existing MySQL data using PHP with AngularJS
  • Remove data from the MySQL table using AngularJS using PHP



For using AngularJS with PHP for Crud operation, here we have a simple one-page application for inserting, updating and deleting data from the MySQL first and last name table using AngularJS with PHP and Bootstrap modal. Now you can develop the AngularJS PHP Crud application step by step.


Step 1 - Make Database Connection


Here we first need to create a simple tbl_sample table in the database and then connect to the 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 creating the table in the MySQL database by writing the following code to the database_connection.php file, you can connect


<?php

//database_connection.php

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



?>




Step 2 - File Structure of AngularJS PHP Crud Application


Below is a brief overview of the files used to create AngularJS PHP Crud. All files are necessary to make this application.


  • b> Angular PHP Crud application
  • angle-datatables.min.js (This is the AngularJS JavaScript library)
  • bootstrap.min.css (This is the Bootstrap stylesheet library)
  • bootstrap.min.js (This is the Bootstrap Javascript library)
  • database_connection.php (PHP file for database connection)
  • datatables.bootstrap.css (This is the Bootstrap Datatables stylesheet library)
  • fetch_data.php (This PHP file to select all data from the MySQL database)
  • index.html (This is the main page of our AngularJS Crud application.)
  • insert.php (this file for inserting, updating and deleting data)
  • jquery.dataTables.min.css (This is the Jquery Datatables stylesheet library.)
  • jquery.dataTables.min.js (This is the JQuery Datatables Javascript library.)
  • jquery.min.js (This Jquery JavaScript library)



Step 3 - Set up Index page


Now we have developed the AngularJS PHP Crud application. In this first step we want to configure the index page for this application. On the index page, we would first like to import the previous Javascript and CSS file into our index page. In the header of the index page we have to write the following HTML code to import Javascript and CSS files.


<!DOCTYPE html>
<html>
 <head>
  <title>AngularJS PHP  CRUD (Create,Read,Update,Delete) Operations</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 see two directives ng-app and ng-controller from AngularJS. With the instruction ng-app we defined the name of the application and with the instruction ng-controller we added the controller to our application.


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


To build the CRUD application first, we would like to list all the MySQL database data on the website. Here we used the Jquery Datatables plugin to display the data from the mysql table in raster format. This way we can easily search and sort data. We used AngularJS with PHP for server-side processing and loading data into the Jquery Datatables add-in. First of all we have a 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>


The code of the previous HTML table shows some modules for angle data tables, e.g. B. datatable and dt-options for Jquery datatables. After that, we need to write the following angular javascript code for the registration module and create the driver.


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

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


We then created an AngularJS function that sends a request to the fetch_data.php page to select all the data in the mysql table tq_sample and display it using this ng-repeat directive under the table complement in the Jquery table.


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


In this function, data is stored in the $ scope.namesData object, and from this object we can display data under the table with the ng-repeat statement that is included in the HTML table definition. This function must be sent to the PHP file. The following server code must be written in the PHP file in order to retrieve all data from the MySQL table and send it to the AngularJS function fetchData.


<?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 searches all the data in the MySQL table and sends it back to the AngularJS function using the json_encode () function in JSON string format. This is a process of displaying data under the JQuery Datatables plug-in using AngularJS with PHP.



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


Now we have started to discuss how we can use Bootstrap Modal with AngularJS to insert or add data to the MySQL table using PHP. So we must first write the following bootstrap warning code on the index.html page to display the success message on the website.


   <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 helps us to display warning messages on the website. In this case we used the ng-show directive. This directive helps us to show and hide HTML elements on the website. And here we wrote a success message in double brackets, the value of which is shown in the model.

After that, we have to write HTML code for bootstrap mode. Because we create a form modal to insert or update existing data. Then we have to make the form modal in Bootstrap. To do this, we need to write the 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 used the bootstrap modal to operate the form. Under the definition of the form, we used the ng-submit statement and defined the submitFrom () function in it. If you use this directive when form data has been submitted, this submitForm () function is called to send form data to the PHP script.

The error when checking the bootstrap warning code was used again under the "Bootstrap" body tag. In this code, we also used the ng-show statement to show and hide modal HTML elements.

Here the modal title data from the angle model were linked. In this case, the text of the modal title is dynamic and changes with different processes.

To search for form data, we used the ng-model directive here. With this directive, we can get HTML element data in AngularJS.

Finally, in bootstrap mode, the hidden label and value of the send button are defined using the data connection method.


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


This code hides the HTML code for the success warning and the error message of the website when it has been loaded into the browser. After that, AngularJS must work to open and close bootstrap mode. To do this, we need to write the 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 that, we need to create an "add" button in our HTML code so we have to write the following code


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


We used the ng-click directive in the button caption and defined an addData () function here. When you click this button, you execute the addData () function. So we have to write the following code for the addData () function.


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


Now you need to execute the submitForm () function, which is called when the form is submitted. In this function we sent the request to insert.php. The page with the form data was submitted with the request. This function is also used to insert and update existing data. Use this function in Both operation.


  $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 to send a request to the server script insert.php. Below is a PHP script to insert data into the mysql table using AngularJS using PHP. In this file, we used the file_get_contents () function for the data we received from the AngularJS function in JSON string format. So with json_decode () we converted to PHP array format. We also wrote a server-side validation code in this code. If the data was inserted correctly, this code sent a response to the AngularJS function in JSON string format using the 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 you have completed the process step by step, you can insert or add data. Now we have to deal with editing or updating existing MySQL table data with AngularJS with PHP and Bootstrap modal. We have already written the bootstrap modal code and now we don't want to create a new modal. We will use the existing bootstrap modal to edit data. First we have to write the function fetchSingleData (). This function searches for specific data based on the value of the id argument. Below you will 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 a request to send to the insert.php file to get certain line data based on the value of the id argument. After successful receipt of the data, this function has assigned a value to the respective form field. This function also sets the hidden identification value of the hidden label, the modal title and the text of the send button. With this function we finally called the openModal () function, which opens the bootstrap mode with 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 added another column in the table to display the Edit button on each row. Ng-click = fetchSingleData (name.id) has been added to each row edit button. This generates a dynamic ID argument value in each row function. When you click the edit button, the fetchSingleData () function is executed and you get data based on the value of the id argument and display that data in bootstrap mode with the full 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 a PHP script to get a specific row of data. Here, data is stored in the output variable $ in matrix form and sent to the AngularJS function in JSON string format.

In the AngularJS function, display the same modal and bootstrap form that we used to insert data. Therefore, we don't want to write any additional code here to send the data update form. We just have to write the PHP code to update the data that we 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 the last CRUD operation that AngularJS uses with PHP. Here we see how we can use AngularJS to delete or delete data from the MySQL table using PHP. To do this, we first have to run an AngularJS function deleteData (). This function is called when we click the Delete button. This function sends a PHP request script to clear data based on the value of the id argument. Below is the AngularJS function code and the HTML code to add another table column to display the dynamic delete button on each row. In the delete button there is a directive ng-click for the 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 to write a PHP script to delete data from the MySQL table. The previous function sent a request to delete data to the insert.php file. This file deletes or deletes a specific row of data based on the value of the 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);



Therefore, we discussed the step-by-step process to make AngularJS Crud Application modal with PHP and Bootstrap. Here we first loaded all the data from the mysql table into the Jquery Datatables plug-in, using AngularJS with PHP. Then we discussed how to insert or add data to the MySQL database using AngularJS PHP and Bootstrap Modal. After inserting data, we saw how to update or edit existing mysql data with AngularJS using PHP and Bootstrap, and finally we saw how we can delete or delete data using PHP with anglejs. This complete single page application uses AngularJS, PHP and Bootstrap modal, because here we can not only insert, update or delete data in the MySQL database, but also search, sort and paginate data.


0 comments:

Post a Comment

Please don't enter any spam link in the comment box.