Friday, 25 May 2018

PHP Login Register Script by using AngularJS



In this tutorial, We will learn How to make PHP Login Register System by using AngularJS. Here we make simple login and register page by using AngularJS. We all know AngularJS is a javascript framework and this library has been written in pure javascript and it is developed and manage by Google. So, in Web development using of AngularJS has been increase. So, many web developers has been use AngularJS for their web development as front-end. For this here we have make this post in which we have describe how to make AngularJS Login Register page by using PHP.

Login and Register is a entry point of any website. So, if we want to access any web system feature then we want to make first registration and after registration we can login into system. So, Login and Registration is a required functionality of any web application. For this here we have make discuss how to create login and registration page in angularjs with PHP and Mysql. This tutorial will useful to AngularJS beginner tutorial becuase here we have discuss PHP Login Register Script by using AngularJS from scratch.

This very simple tutorial which will helps to AngularJS beginner developers to crate simple Register and Login page by using AngularJS with PHP and Mysql. Because by using AngularJS we can make single page web application. So here also we will make login and register form in single page. In this single page login and register application by using AngularJS when page has been load into browser then we can only see Login page on our index page. And suppose we want to go to register page then by click to Register link then AngularJS register form will be visible on web page and AngularJS login form will be hide. After successfully register into system then we can loign into system. In Login and Register we have also use PHP server side validation with AngularJS. After login into system page also redirect to index page. So in single page we have make login page, register page and after login and enter into system also in index page. For check user login into system or not for this we have use PHP Session variable. So, this way we have make single page Login Register system by using AngularJS with PHP & Mysql.









Source Code


index.php



<?php

//index.php

session_start();

?>
<!DOCTYPE html>
<html>
 <head>
  <title>AngularJS Register Login Script using PHP Mysql</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <style>
  .form_style
  {
   width: 600px;
   margin: 0 auto;
  }
  </style>
 </head>
 <body>
  <br />
   <h3 align="center">AngularJS Register Login Script using PHP Mysql</h3>
  <br />

  <div ng-app="login_register_app" ng-controller="login_register_controller" class="container form_style">
   <?php
   if(!isset($_SESSION["name"]))
   {
   ?>
   <div class="alert {{alertClass}} alert-dismissible" ng-show="alertMsg">
    <a href="#" class="close" ng-click="closeMsg()" aria-label="close">&times;</a>
    {{alertMessage}}
   </div>

   <div class="panel panel-default" ng-show="login_form">
    <div class="panel-heading">
     <h3 class="panel-title">Login</h3>
    </div>
    <div class="panel-body">
     <form method="post" ng-submit="submitLogin()">
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="text" name="email" ng-model="loginData.email" class="form-control" />
      </div>
      <div class="form-group">
       <label>Enter Your Password</label>
       <input type="password" name="password" ng-model="loginData.password" class="form-control" />
      </div>
      <div class="form-group" align="center">
       <input type="submit" name="login" class="btn btn-primary" value="Login" />
       <br />
       <input type="button" name="register_link" class="btn btn-primary btn-link" ng-click="showRegister()" value="Register" />
      </div>
     </form>
    </div>
   </div>

   <div class="panel panel-default" ng-show="register_form">
    <div class="panel-heading">
     <h3 class="panel-title">Register</h3>
    </div>
    <div class="panel-body">
     <form method="post" ng-submit="submitRegister()">
      <div class="form-group">
       <label>Enter Your Name</label>
       <input type="text" name="name" ng-model="registerData.name" class="form-control" />
      </div>
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="text" name="email" ng-model="registerData.email" class="form-control" />
      </div>
      <div class="form-group">
       <label>Enter Your Password</label>
       <input type="password" name="password" ng-model="registerData.password" class="form-control" />
      </div>
      <div class="form-group" align="center">
       <input type="submit" name="register" class="btn btn-primary" value="Register" />
       <br />
       <input type="button" name="login_link" class="btn btn-primary btn-link" ng-click="showLogin()" value="Login" />
      </div>
     </form>
    </div>
   </div>
   <?php
   }
   else
   {
   ?>
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Welcome to system</h3>
    </div>
    <div class="panel-body">
     <h1>Welcome - <?php echo $_SESSION["name"];?></h1>
     <a href="logout.php">Logout</a>
    </div>
   </div>
   <?php
   }
   ?>

  </div>
 </body>
</html>

<script>
var app = angular.module('login_register_app', []);
app.controller('login_register_controller', function($scope, $http){
 $scope.closeMsg = function(){
  $scope.alertMsg = false;
 };

 $scope.login_form = true;

 $scope.showRegister = function(){
  $scope.login_form = false;
  $scope.register_form = true;
  $scope.alertMsg = false;
 };

 $scope.showLogin = function(){
  $scope.register_form = false;
  $scope.login_form = true;
  $scope.alertMsg = false;
 };

 $scope.submitRegister = function(){
  $http({
   method:"POST",
   url:"register.php",
   data:$scope.registerData
  }).success(function(data){
   $scope.alertMsg = true;
   if(data.error != '')
   {
    $scope.alertClass = 'alert-danger';
    $scope.alertMessage = data.error;
   }
   else
   {
    $scope.alertClass = 'alert-success';
    $scope.alertMessage = data.message;
    $scope.registerData = {};
   }
  });
 };

 $scope.submitLogin = function(){
  $http({
   method:"POST",
   url:"login.php",
   data:$scope.loginData
  }).success(function(data){
   if(data.error != '')
   {
    $scope.alertMsg = true;
    $scope.alertClass = 'alert-danger';
    $scope.alertMessage = data.error;
   }
   else
   {
    location.reload();
   }
  });
 };

});
</script>


database_connection.php



<?php

//database_connection.php

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

?>


register.php



<?php

//register.php

include('database_connection.php');

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

$message = '';
$validation_error = '';

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

if(empty($form_data->email))
{
 $error[] = 'Email is Required';
}
else
{
 if(!filter_var($form_data->email, FILTER_VALIDATE_EMAIL))
 {
  $error[] = 'Invalid Email Format';
 }
 else
 {
  $data[':email'] = $form_data->email;
 }
}

if(empty($form_data->password))
{
 $error[] = 'Password is Required';
}
else
{
 $data[':password'] = password_hash($form_data->password, PASSWORD_DEFAULT);
}

if(empty($error))
{
 $query = "
 INSERT INTO register (name, email, password) VALUES (:name, :email, :password)
 ";
 $statement = $connect->prepare($query);
 if($statement->execute($data))
 {
  $message = 'Registration Completed';
 }
}
else
{
 $validation_error = implode(", ", $error);
}

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

echo json_encode($output);


?>


login.php



<?php

//login.php

include('database_connection.php');

session_start();

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

$validation_error = '';

if(empty($form_data->email))
{
 $error[] = 'Email is Required';
}
else
{
 if(!filter_var($form_data->email, FILTER_VALIDATE_EMAIL))
 {
  $error[] = 'Invalid Email Format';
 }
 else
 {
  $data[':email'] = $form_data->email;
 }
}

if(empty($form_data->password))
{
 $error[] = 'Password is Required';
}

if(empty($error))
{
 $query = "
 SELECT * FROM register 
 WHERE email = :email
 ";
 $statement = $connect->prepare($query);
 if($statement->execute($data))
 {
  $result = $statement->fetchAll();
  if($statement->rowCount() > 0)
  {
   foreach($result as $row)
   {
    if(password_verify($form_data->password, $row["password"]))
    {
     $_SESSION["name"] = $row["name"];
    }
    else
    {
     $validation_error = 'Wrong Password';
    }
   }
  }
  else
  {
   $validation_error = 'Wrong Email';
  }
 }
}
else
{
 $validation_error = implode(", ", $error);
}

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

echo json_encode($output);

?>


logout.php



<?php

//logout.php

session_start();

session_destroy();

header("location:index.php");


?>


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `register`
--

CREATE TABLE `register` (
  `id` int(11) NOT NULL,
  `name` varchar(250) NOT NULL,
  `email` varchar(250) NOT NULL,
  `password` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `register`
--
ALTER TABLE `register`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;

Monday, 21 May 2018

How to Create Dynamic Timeline in PHP



From this post you can learn new things like How to make dynamic timeline functionality for your websites in PHP. Here we have discuss how can we display our past event on website in timeline format. For this here we have decide name make one tutorial in which we have learn how can we will display our past event in timeline format. For this we have figureout one Jquery timeline plugin. With the help of this plugin and our PHP scripting code we have make dynamic timeline in PHP and Mysql. So, How can we create timeline in PHP. This feature we have discuss in this post.

If we want to make dynamic timeline in PHP, then first we want to store our past event data in our mysql database. So, by using this PHP code we can fetch data from Mysql database and display on webpage. Here we have fetch data which want to display in timeline format. So, here we can create dynamic timeline in PHP with help of Mysql database. In many of website we can see timeline on their website. So, here we have already make something like this type of feature. With help of PHP and Mysql we can solve our server side part.

But for client side, we want to display timeline in stylish graphical format. For this we have use Jquery Timeline plugin. With help of this plugin we can display timeline in horizontal direction or vertical direction which is depend on us. This Jquery Timeline plugin make responsive timeline which it will easily fit on any devices like Desktop computer, laptop, tablet or even mobile device also. So, by using this plugin we can not only make horizontal or vertical direction timeline but also it has make responsive timeline. So, Here we have use this Jquery Timeline plugin with PHP and Mysql and make dynamic timeline. Below you can find complete source code of How to create timeline in PHP and online demo also.









Source Code



<?php

//index.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$query = "SELECT * FROM timeline ORDER BY id ASC";

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

$statement->execute();

$result = $statement->fetchAll();

?>

<html>  
    <head>  
        <title>How to Create Dynamic Timeline in PHP</title>
        <script src="js/jquery.js"></script>
        <script src="js/timeline.min.js"></script>
  <link rel="stylesheet" href="css/bootstrap.min.css" />
        <link rel="stylesheet" href="css/timeline.min.css" />
  
    </head>  
    <body>  
        <div class="container">
   <br />
   <h3 align="center"><a href="">How to Create Dynamic Timeline in PHP</a></a></h3><br />
   <div class="panel panel-default">
    <div class="panel-heading">
                    <h3 class="panel-title">Our Journey</h3>
                </div>
                <div class="panel-body">
                 <div class="timeline">
                  <div class="timeline__wrap">
                   <div class="timeline__items">
                   <?php 
                   foreach($result as $row)
                   {
                   ?>
                    <div class="timeline__item">
                     <div class="timeline__content">
                      <h2><?php echo $row["year"]; ?></h2>
                      <p><?php echo $row["comment"];?></p>
                     </div>
                    </div>
                   <?php
                   }
                   ?>
                   </div>
                  </div>
                 </div>
                </div>
   </div>
  </div>
    </body>  
</html>

<script>
$(document).ready(function(){
 jQuery('.timeline').timeline({
  //mode: 'horizontal',
  //visibleItems: 4
  //Remove this comment for see Timeline in Horizontal Format otherwise it will display in Vertical Direction Timeline
 });
});
</script>





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.




Tuesday, 15 May 2018

How to Export Mysql Data to Excel File in Laravel



We have share new web tutorial on Laravel and in this post we have discuss how to export mysql data in laravel by using Laravel maatwebsite package for excel. By using this package we will seen how can we export data from mysql database to Excel spreadsheet in Laravel framework. Maatwebsite Laravel package give us very large functionality for export data into excel or csv file format in Laravel.

If we have developed very big ERP or e-commerce web application in Laravel framework then at that time we have required export of our mysql table data to excel format for reducing our database entry time in excel or csv file. So, by on single click we can transfer large amount of data in excel spreadsheet for our required purpose. We have already publish how to export data to excel sheet in PHP and codeigniter framework by using PHPExcel library. But in Laravel framework we will use maatwebsite package for excel file.

So, in this post we will seen how to make excel export functionality in our Laravel application by using maatwebsite package for excel. Here we have discuss step by step process for how to use maatwebsite package in Laravel application for export mysql table data to excel sheet.







Step 1 : Install maatwebsite/excel package


For install maatwebsite/excel package in our Laravel application we have to write following command in our command prompt.


composer require maatwebsite/excel


This command will download and install this package in our Laravel framework. After this we want to register this package in our application for we have to go to config/app.php file and add service provider and aliase details.


'providers' => [
 ....

 Maatwebsite\Excel\ExcelServiceProvider::class,

],

'aliases' => [

 ....

 'Excel' => Maatwebsite\Excel\Facades\Excel::class,

],


Step 2 : Create Controller


First we want to make one controller for handle http request in our laravel application. By using this controller we will display mysql data on web page and then after it will also handle request for export data to excel. First we want to write following command in command prompt for make controller in our laravel application.


php artisan make:controller ExportExcelController


This command will make ExportExcelController.php file under app/Http/Controllers folder. In this controller we have make two method. First index() method will display mysql table data on web page and second excel() method will export mysql table data to excel file.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Excel;

class ExportExcelController extends Controller
{
    function index()
    {
     $customer_data = DB::table('tbl_customer')->get();
     return view('export_excel')->with('customer_data', $customer_data);
    }

    function excel()
    {
     $customer_data = DB::table('tbl_customer')->get()->toArray();
     $customer_array[] = array('Customer Name', 'Address', 'City', 'Postal Code', 'Country');
     foreach($customer_data as $customer)
     {
      $customer_array[] = array(
       'Customer Name'  => $customer->CustomerName,
       'Address'   => $customer->Address,
       'City'    => $customer->City,
       'Postal Code'  => $customer->PostalCode,
       'Country'   => $customer->Country
      );
     }
     Excel::create('Customer Data', function($excel) use ($customer_array){
      $excel->setTitle('Customer Data');
      $excel->sheet('Customer Data', function($sheet) use ($customer_array){
       $sheet->fromArray($customer_array, null, 'A1', false, false);
      });
     })->download('xlsx');
    }
}

?>


Step 3 : Create View


After this for display output in browser we have to create view files under resources/views folder. This file for display output of laravel application on web page.



<!--
 export_excel.blade.php
!-->

<!DOCTYPE html>
<html>
 <head>
  <title>Export Data to Excel in Laravel using Maatwebsite</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.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.7/js/bootstrap.min.js"></script>
  <style type="text/css">
   .box{
    width:600px;
    margin:0 auto;
    border:1px solid #ccc;
   }
  </style>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Export Data to Excel in Laravel using Maatwebsite</h3><br />
   <div align="center">
    <a href="{{ route('export_excel.excel') }}" class="btn btn-success">Export to Excel</a>
   </div>
   <br />
   <div class="table-responsive">
    <table class="table table-striped table-bordered">
     <tr>
      <td>Customer Name</td>
      <td>Address</td>
      <td>City</td>
      <td>Postal Code</td>
      <td>Country</td>
     </tr>
     @foreach($customer_data as $customer)
     <tr>
      <td>{{ $customer->CustomerName }}</td>
      <td>{{ $customer->Address }}</td>
      <td>{{ $customer->City }}</td>
      <td>{{ $customer->PostalCode }}</td>
      <td>{{ $customer->Country }}</td>
     </tr>
     @endforeach
    </table>
   </div>
   
  </div>
 </body>
</html>



Step 4 : Set Route


Lastly we want to set route for index() and excel() method in our application. For this we have to go to routes/web.php file and write following code for set route for above two method.


<?php
//routes/web.php

Route::get('/export_excel', 'ExportExcelController@index');

Route::get('/export_excel/excel', 'ExportExcelController@excel')->name('export_excel.excel');

?>


So here our code is ready for How to export mysql table data to excel file by using maatwebsite/excel package in Laravel.

Saturday, 12 May 2018

How to Make Simple Crud Rest Api in PHP with Mysql



We have already learned how can we do Create, Read, Update and delete CRUD operation by using PHP PDO, Mysql and Ajax. But in this post we have discuss how can do this all CRUD operation by using PHP api with Ajax. So, here we will make simple PHP Restful Api step by step.

What is REST Api in PHP?


But First we need to know what is Restful Api and what is the use of this Api in web development. Here REST means "REpresentational State Transfer". It is a simple method for manage information on internet. REST ideas are referred to as simple resources and rendering of resources should be stateless. It is mainly displayed by JSON format.

Same way API means "Application Programming Interface". This Api is place or guideline which allows one set of web application can be communicate with another. In that guidelines we can insert, update and delete data operation.

Rest API allow you web application to communicate with one or various different application by using REST concepts.

Why should we need PHP Rest API?


There are many PHP web application in which REST API is required because it is a simplest way to insert, update or delete data between various application over the internet by using HTTP protocol. REST API can be used by any type of web application which has been connected with internet. If any information from an web application has been inserted, updated or deleted by using another web application that means it has use REST API.

Now we have make a RESTful web service in PHP for CRUD operations. The REST API has been used by creating HTTP GET or POST or PUT or DELETE operation from client to server or server to get or put data. The REST API based web services can be given output in different format like CSV JSON etc. In this tutorial we will learn how to make simple REST API by using PHP Mysql. Now let's start learn how to create API in PHP.



File Structure


Following are the file structure of PHP REST API for CRUD operation.


  • api //In this folder we have store PHP API File
    • Api.php
    • //This is API class for Insert Update Delete
    • test_api.php
    • //This file will handle API request.
  • work //In this folder we will make file for send API request
    • index.php
    • fetch.php
    • action.php

How to Display or Fetch data by using PHP REST API


First we want to learn how to select all or fetch all data from Mysql database and display on web page. For this we have use Ajax with PHP. For this we have make Ajax function and this function has send request to fetch.php page and this page has send request to API which we have make under api/test_api.php. This page received api request for API class which we have make.

work/index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Mysql REST API CRUD</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>
 </head>
 <body>
  <div class="container">
   <br />
   
   <h3 align="center">PHP Mysql REST API CRUD</h3>
   <br />
   <div align="right" style="margin-bottom:5px;">
    <button type="button" name="add_button" id="add_button" class="btn btn-success btn-xs">Add</button>
   </div>

   <div class="table-responsive">
    <table 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></tbody>
    </table>
   </div>
  </div>
 </body>
</html>

<script type="text/javascript">
$(document).ready(function(){

 fetch_data();

 function fetch_data()
 {
  $.ajax({
   url:"fetch.php",
   success:function(data)
   {
    $('tbody').html(data);
   }
  })
 }
</script>


work/fetch.php



<?php

//fetch.php

$api_url = "http://localhost/tutorial/rest-api-crud-using-php/api/test_api.php?action=fetch_all";

$client = curl_init($api_url);

curl_setopt($client, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($client);

$result = json_decode($response);

$output = '';

if(count($result) > 0)
{
 foreach($result as $row)
 {
  $output .= '
  <tr>
   <td>'.$row->first_name.'</td>
   <td>'.$row->last_name.'</td>
   <td><button type="button" name="edit" class="btn btn-warning btn-xs edit" id="'.$row->id.'">Edit</button></td>
   <td><button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row->id.'">Delete</button></td>
  </tr>
  ';
 }
}
else
{
 $output .= '
 <tr>
  <td colspan="4" align="center">No Data Found</td>
 </tr>
 ';
}

echo $output;

?>


api/test_api.php



<?php

//test_api.php

include('Api.php');

$api_object = new API();

if($_GET["action"] == 'fetch_all')
{
 $data = $api_object->fetch_all();
}

echo json_encode($data);

?>


api/Api.php



<?php

//Api.php

class API
{
 private $connect = '';

 function __construct()
 {
  $this->database_connection();
 }

 function database_connection()
 {
  $this->connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 }

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

?>





How to Insert or Add Data into Mysql table using PHP REST API


If you have web application and if you want to make Android or IOS application then at that time from that application you want to Insert or Add data into your web application database then at that time PHP web services are use. PHP webservices has been created by using PHP api. So here we have learn how to insert or add data into Mysql table by using API from any mobile application. Here we have we have use Ajax for insert data into mysql table by using PHP api. For this we have send Ajax request to from index.php to action.php and on action.php we have send api request to api/test_api.php for insert or add data into mysql table. On api/test_api.php it has run method for insert or add data of api/Api.php. Below you can find complete code for insert data using PHP API.

work/index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Mysql REST API CRUD</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>
 </head>
 <body>
  <div class="container">
   <br />
   
   <h3 align="center">PHP Mysql REST API CRUD</h3>
   <br />
   <div align="right" style="margin-bottom:5px;">
    <button type="button" name="add_button" id="add_button" class="btn btn-success btn-xs">Add</button>
   </div>

   <div class="table-responsive">
    <table 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></tbody>
    </table>
   </div>
  </div>
 </body>
</html>

<div id="apicrudModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <form method="post" id="api_crud_form">
    <div class="modal-header">
           <button type="button" class="close" data-dismiss="modal">&times;</button>
           <h4 class="modal-title">Add Data</h4>
         </div>
         <div class="modal-body">
          <div class="form-group">
            <label>Enter First Name</label>
            <input type="text" name="first_name" id="first_name" class="form-control" />
           </div>
           <div class="form-group">
            <label>Enter Last Name</label>
            <input type="text" name="last_name" id="last_name" class="form-control" />
           </div>
       </div>
       <div class="modal-footer">
        <input type="hidden" name="hidden_id" id="hidden_id" />
        <input type="hidden" name="action" id="action" value="insert" />
        <input type="submit" name="button_action" id="button_action" class="btn btn-info" value="Insert" />
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
         </div>
   </form>
  </div>
   </div>
</div>


<script type="text/javascript">
$(document).ready(function(){

 fetch_data();

 function fetch_data()
 {
  $.ajax({
   url:"fetch.php",
   success:function(data)
   {
    $('tbody').html(data);
   }
  })
 }

 $('#add_button').click(function(){
  $('#action').val('insert');
  $('#button_action').val('Insert');
  $('.modal-title').text('Add Data');
  $('#apicrudModal').modal('show');
 });

 $('#api_crud_form').on('submit', function(event){
  event.preventDefault();
  if($('#first_name').val() == '')
  {
   alert("Enter First Name");
  }
  else if($('#last_name').val() == '')
  {
   alert("Enter Last Name");
  }
  else
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"action.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     fetch_data();
     $('#api_crud_form')[0].reset();
     $('#apicrudModal').modal('hide');
     if(data == 'insert')
     {
      alert("Data Inserted using PHP API");
     }
     if(data == 'update')
     {
      alert("Data Updated using PHP API");
     }
    }
   });
  }
 });

</script>


work/action.php



<?php

//action.php

if(isset($_POST["action"]))
{
 if($_POST["action"] == 'insert')
 {
  $form_data = array(
   'first_name' => $_POST['first_name'],
   'last_name'  => $_POST['last_name']
  );
  $api_url = "http://localhost/tutorial/rest-api-crud-using-php/api/test_api.php?action=insert";
  $client = curl_init($api_url);
  curl_setopt($client, CURLOPT_POST, true);
  curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);
  curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($client);
  curl_close($client);
  $result = json_decode($response, true);
  foreach($result as $keys => $values)
  {
   if($result[$keys]['success'] == '1')
   {
    echo 'insert';
   }
   else
   {
    echo 'error';
   }
  }
 }
?>


api/test_api.php



<?php

//test_api.php

include('Api.php');

$api_object = new API();

if($_GET["action"] == 'insert')
{
 $data = $api_object->insert();
}

echo json_encode($data);

?>


api/Api.php



<?php

//Api.php

class API
{
 private $connect = '';

 function __construct()
 {
  $this->database_connection();
 }

 function database_connection()
 {
  $this->connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 }

 function insert()
 {
  if(isset($_POST["first_name"]))
  {
   $form_data = array(
    ':first_name'  => $_POST["first_name"],
    ':last_name'  => $_POST["last_name"]
   );
   $query = "
   INSERT INTO tbl_sample 
   (first_name, last_name) VALUES 
   (:first_name, :last_name)
   ";
   $statement = $this->connect->prepare($query);
   if($statement->execute($form_data))
   {
    $data[] = array(
     'success' => '1'
    );
   }
   else
   {
    $data[] = array(
     'success' => '0'
    );
   }
  }
  else
  {
   $data[] = array(
    'success' => '0'
   );
  }
  return $data;
 }

?>


How to Update or Edit Mysql data using PHP API


Above we have seen how to insert or add data using PHP API. But suppose we want to make some changes in data which we have inserted or store under mysql table from any Mobile application. Then at that time PHP API can we used by using PHP API we can edit or update our web application data remotly from any location and from any web device which has been connected with internet. We have to just send update or edit data request to PHP API. Below you can find complete source code for how to update or edit Mysql table data by using PHP Restful API.

work/index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Mysql REST API CRUD</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>
 </head>
 <body>
  <div class="container">
   <br />
   
   <h3 align="center">PHP Mysql REST API CRUD</h3>
   <br />
   <div align="right" style="margin-bottom:5px;">
    <button type="button" name="add_button" id="add_button" class="btn btn-success btn-xs">Add</button>
   </div>

   <div class="table-responsive">
    <table 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></tbody>
    </table>
   </div>
  </div>
 </body>
</html>

<div id="apicrudModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <form method="post" id="api_crud_form">
    <div class="modal-header">
           <button type="button" class="close" data-dismiss="modal">&times;</button>
           <h4 class="modal-title">Add Data</h4>
         </div>
         <div class="modal-body">
          <div class="form-group">
            <label>Enter First Name</label>
            <input type="text" name="first_name" id="first_name" class="form-control" />
           </div>
           <div class="form-group">
            <label>Enter Last Name</label>
            <input type="text" name="last_name" id="last_name" class="form-control" />
           </div>
       </div>
       <div class="modal-footer">
        <input type="hidden" name="hidden_id" id="hidden_id" />
        <input type="hidden" name="action" id="action" value="insert" />
        <input type="submit" name="button_action" id="button_action" class="btn btn-info" value="Insert" />
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
         </div>
   </form>
  </div>
   </div>
</div>


<script type="text/javascript">
$(document).ready(function(){

 fetch_data();

 function fetch_data()
 {
  $.ajax({
   url:"fetch.php",
   success:function(data)
   {
    $('tbody').html(data);
   }
  })
 }

 $('#add_button').click(function(){
  $('#action').val('insert');
  $('#button_action').val('Insert');
  $('.modal-title').text('Add Data');
  $('#apicrudModal').modal('show');
 });

 $('#api_crud_form').on('submit', function(event){
  event.preventDefault();
  if($('#first_name').val() == '')
  {
   alert("Enter First Name");
  }
  else if($('#last_name').val() == '')
  {
   alert("Enter Last Name");
  }
  else
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"action.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     fetch_data();
     $('#api_crud_form')[0].reset();
     $('#apicrudModal').modal('hide');
     if(data == 'insert')
     {
      alert("Data Inserted using PHP API");
     }
     if(data == 'update')
     {
      alert("Data Updated using PHP API");
     }
    }
   });
  }
 });

 $(document).on('click', '.edit', function(){
  var id = $(this).attr('id');
  var action = 'fetch_single';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{id:id, action:action},
   dataType:"json",
   success:function(data)
   {
    $('#hidden_id').val(id);
    $('#first_name').val(data.first_name);
    $('#last_name').val(data.last_name);
    $('#action').val('update');
    $('#button_action').val('Update');
    $('.modal-title').text('Edit Data');
    $('#apicrudModal').modal('show');
   }
  })
 });

</script>


work/action.php



<?php

//action.php

if(isset($_POST["action"]))
{

 if($_POST["action"] == 'fetch_single')
 {
  $id = $_POST["id"];
  $api_url = "http://localhost/tutorial/rest-api-crud-using-php/api/test_api.php?action=fetch_single&id=".$id."";
  $client = curl_init($api_url);
  curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($client);
  echo $response;
 }

 if($_POST["action"] == 'update')
 {
  $form_data = array(
   'first_name' => $_POST['first_name'],
   'last_name'  => $_POST['last_name'],
   'id'   => $_POST['hidden_id']
  );
  $api_url = "http://localhost/tutorial/rest-api-crud-using-php/api/test_api.php?action=update";
  $client = curl_init($api_url);
  curl_setopt($client, CURLOPT_POST, true);
  curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);
  curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($client);
  curl_close($client);
  $result = json_decode($response, true);
  foreach($result as $keys => $values)
  {
   if($result[$keys]['success'] == '1')
   {
    echo 'update';
   }
   else
   {
    echo 'error';
   }
  }
 }

?>


api/test_api.php



<?php

//test_api.php

include('Api.php');

$api_object = new API();


if($_GET["action"] == 'fetch_single')
{
 $data = $api_object->fetch_single($_GET["id"]);
}

if($_GET["action"] == 'update')
{
 $data = $api_object->update();
}

echo json_encode($data);

?>


api/Api.php



<?php

//Api.php

class API
{
 private $connect = '';

 function __construct()
 {
  $this->database_connection();
 }

 function database_connection()
 {
  $this->connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 }

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

 function fetch_single($id)
 {
  $query = "SELECT * FROM tbl_sample WHERE id='".$id."'";
  $statement = $this->connect->prepare($query);
  if($statement->execute())
  {
   foreach($statement->fetchAll() as $row)
   {
    $data['first_name'] = $row['first_name'];
    $data['last_name'] = $row['last_name'];
   }
   return $data;
  }
 }

 function update()
 {
  if(isset($_POST["first_name"]))
  {
   $form_data = array(
    ':first_name' => $_POST['first_name'],
    ':last_name' => $_POST['last_name'],
    ':id'   => $_POST['id']
   );
   $query = "
   UPDATE tbl_sample 
   SET first_name = :first_name, last_name = :last_name 
   WHERE id = :id
   ";
   $statement = $this->connect->prepare($query);
   if($statement->execute($form_data))
   {
    $data[] = array(
     'success' => '1'
    );
   }
   else
   {
    $data[] = array(
     'success' => '0'
    );
   }
  }
  else
  {
   $data[] = array(
    'success' => '0'
   );
  }
  return $data;
 }

?>


How to Delete or Remove data from Mysql using PHP API


This is last operation of CRUD and here we want to learn how can we delete or remove Mysql table data by using PHP REST API. API we can access from any place and from any device just we have access key particular API. So, suppose we want to just delete or remove some information from wep application by using web device application. So, from application we have to just send request to API from delete or remove particular data from your database. API will remove or delete data and it will send request back to particular application from where it has received request. Below you find how to delete or remove Mysql table data by using PHP API with Ajax.

work/index.php



<!DOCTYPE html>
<html>
 <head>
  <title>PHP Mysql REST API CRUD</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>
 </head>
 <body>
  <div class="container">
   <br />
   
   <h3 align="center">PHP Mysql REST API CRUD</h3>
   <br />
   <div align="right" style="margin-bottom:5px;">
    <button type="button" name="add_button" id="add_button" class="btn btn-success btn-xs">Add</button>
   </div>

   <div class="table-responsive">
    <table 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></tbody>
    </table>
   </div>
  </div>
 </body>
</html>

<div id="apicrudModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <form method="post" id="api_crud_form">
    <div class="modal-header">
           <button type="button" class="close" data-dismiss="modal">&times;</button>
           <h4 class="modal-title">Add Data</h4>
         </div>
         <div class="modal-body">
          <div class="form-group">
            <label>Enter First Name</label>
            <input type="text" name="first_name" id="first_name" class="form-control" />
           </div>
           <div class="form-group">
            <label>Enter Last Name</label>
            <input type="text" name="last_name" id="last_name" class="form-control" />
           </div>
       </div>
       <div class="modal-footer">
        <input type="hidden" name="hidden_id" id="hidden_id" />
        <input type="hidden" name="action" id="action" value="insert" />
        <input type="submit" name="button_action" id="button_action" class="btn btn-info" value="Insert" />
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
         </div>
   </form>
  </div>
   </div>
</div>


<script type="text/javascript">
$(document).ready(function(){

 fetch_data();

 function fetch_data()
 {
  $.ajax({
   url:"fetch.php",
   success:function(data)
   {
    $('tbody').html(data);
   }
  })
 }

 $('#add_button').click(function(){
  $('#action').val('insert');
  $('#button_action').val('Insert');
  $('.modal-title').text('Add Data');
  $('#apicrudModal').modal('show');
 });

 $('#api_crud_form').on('submit', function(event){
  event.preventDefault();
  if($('#first_name').val() == '')
  {
   alert("Enter First Name");
  }
  else if($('#last_name').val() == '')
  {
   alert("Enter Last Name");
  }
  else
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"action.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     fetch_data();
     $('#api_crud_form')[0].reset();
     $('#apicrudModal').modal('hide');
     if(data == 'insert')
     {
      alert("Data Inserted using PHP API");
     }
     if(data == 'update')
     {
      alert("Data Updated using PHP API");
     }
    }
   });
  }
 });

 $(document).on('click', '.edit', function(){
  var id = $(this).attr('id');
  var action = 'fetch_single';
  $.ajax({
   url:"action.php",
   method:"POST",
   data:{id:id, action:action},
   dataType:"json",
   success:function(data)
   {
    $('#hidden_id').val(id);
    $('#first_name').val(data.first_name);
    $('#last_name').val(data.last_name);
    $('#action').val('update');
    $('#button_action').val('Update');
    $('.modal-title').text('Edit Data');
    $('#apicrudModal').modal('show');
   }
  })
 });

 $(document).on('click', '.delete', function(){
  var id = $(this).attr("id");
  var action = 'delete';
  if(confirm("Are you sure you want to remove this data using PHP API?"))
  {
   $.ajax({
    url:"action.php",
    method:"POST",
    data:{id:id, action:action},
    success:function(data)
    {
     fetch_data();
     alert("Data Deleted using PHP API");
    }
   });
  }
 });

});
</script>


work/action.php



<?php

//action.php

if(isset($_POST["action"]))
{
 
 if($_POST["action"] == 'delete')
 {
  $id = $_POST['id'];
  $api_url = "http://localhost/tutorial/rest-api-crud-using-php/api/test_api.php?action=delete&id=".$id."";
  $client = curl_init($api_url);
  curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($client);
  echo $response;
 }
}


?>


api/test_api.php



<?php

//test_api.php

include('Api.php');

$api_object = new API();

if($_GET["action"] == 'delete')
{
 $data = $api_object->delete($_GET["id"]);
}

echo json_encode($data);

?>


api/Api.php


<?php

//Api.php

class API
{
 private $connect = '';

 function __construct()
 {
  $this->database_connection();
 }

 function database_connection()
 {
  $this->connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 }

 function delete($id)
 {
  $query = "DELETE FROM tbl_sample WHERE id = '".$id."'";
  $statement = $this->connect->prepare($query);
  if($statement->execute())
  {
   $data[] = array(
    'success' => '1'
   );
  }
  else
  {
   $data[] = array(
    'success' => '0'
   );
  }
  return $data;
 }
}

?>


So, this is complete web tutorial on How to Create RESTful API in PHP and by using PHP API how to insert, update and delete data from Mysql table. If you want to download complete source code of PHP RESTful API then you have to click on below link.




Tuesday, 8 May 2018

Simple PHP Shopping Cart using Cookies


Do you know how to make Shopping Cart by using PHP Cookies then you have come on right place because in this post we have discuss how to make PHP Mysql Online shopping cart by using Cookies Variable. In this tutorial we have describe step by step how create PHP shopping cart by using Cookies. We have publish many tutorial on PHP Shopping cart but in all shopping cart tutorial we have use PHP Session but here we have developed Shopping cart which is based on PHP Cookies. This is PHP shopping cart tutorial by using COOKIES.

We all know COOKIES variable data has been stored on client side while SESSION variable data has been stored on server side. So, if we have use SESSION variable for store shopping cart data then that data has been stored on our server but if we want to make light shopping cart which will reduce load on our ecommerce site then we can use COOKIES variable for store shopping cart data which will be store on client browser. So, by using PHP COOKIES variable we can also developed ecommerce shopping cart by using PHP. We all know SESSION variable has been access through our system from any web page, same way we can also access COOKIES data from any page on systm.

Shopping Cart data has been very important information for any ecommerce website and it has been generated on user activity on our website. So PHP Session code has been works in this case and it is used by many websites for this type of data. But now a days it is more advisable to use PHP COOKIES for ecommerce shopping cart. Because cookies variable has been used for remember infomation. So in this we can also store shopping cart data also. So, if page has been refresh then that will not be lost. So, this is the reason for use PHP COOKIES for make a shopping cart. There is one more reason for use COOKIES for shopping cart. We all know if we add some item into shopping cart and it we have close the browser or shut down computer and restart computer and again open browser then we can fetch our shopping cart data from COOKIES because it has been store under client browser.

So, there are other many reason for use COOKIES for make PHP Shopping cart. Below you can find complete source code for PHP Shopping cart by using COOKIES.









Source Code


index.php



<?php 

//index.php

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

$message = '';

if(isset($_POST["add_to_cart"]))
{
 if(isset($_COOKIE["shopping_cart"]))
 {
  $cookie_data = stripslashes($_COOKIE['shopping_cart']);

  $cart_data = json_decode($cookie_data, true);
 }
 else
 {
  $cart_data = array();
 }

 $item_id_list = array_column($cart_data, 'item_id');

 if(in_array($_POST["hidden_id"], $item_id_list))
 {
  foreach($cart_data as $keys => $values)
  {
   if($cart_data[$keys]["item_id"] == $_POST["hidden_id"])
   {
    $cart_data[$keys]["item_quantity"] = $cart_data[$keys]["item_quantity"] + $_POST["quantity"];
   }
  }
 }
 else
 {
  $item_array = array(
   'item_id'   => $_POST["hidden_id"],
   'item_name'   => $_POST["hidden_name"],
   'item_price'  => $_POST["hidden_price"],
   'item_quantity'  => $_POST["quantity"]
  );
  $cart_data[] = $item_array;
 }

 
 $item_data = json_encode($cart_data);
 setcookie('shopping_cart', $item_data, time() + (86400 * 30));
 header("location:index.php?success=1");
}

if(isset($_GET["action"]))
{
 if($_GET["action"] == "delete")
 {
  $cookie_data = stripslashes($_COOKIE['shopping_cart']);
  $cart_data = json_decode($cookie_data, true);
  foreach($cart_data as $keys => $values)
  {
   if($cart_data[$keys]['item_id'] == $_GET["id"])
   {
    unset($cart_data[$keys]);
    $item_data = json_encode($cart_data);
    setcookie("shopping_cart", $item_data, time() + (86400 * 30));
    header("location:index.php?remove=1");
   }
  }
 }
 if($_GET["action"] == "clear")
 {
  setcookie("shopping_cart", "", time() - 3600);
  header("location:index.php?clearall=1");
 }
}

if(isset($_GET["success"]))
{
 $message = '
 <div class="alert alert-success alert-dismissible">
    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
    Item Added into Cart
 </div>
 ';
}

if(isset($_GET["remove"]))
{
 $message = '
 <div class="alert alert-success alert-dismissible">
  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
  Item removed from Cart
 </div>
 ';
}
if(isset($_GET["clearall"]))
{
 $message = '
 <div class="alert alert-success alert-dismissible">
  <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
  Your Shopping Cart has been clear...
 </div>
 ';
}


?>
<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Demo | Simple PHP Mysql Shopping Cart</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>
 </head>
 <body>
  <br />
  <div class="container">
   <br />
   <h3 align="center">Simple PHP Mysql Shopping Cart using Cookies</h3><br />
   <br /><br />
   <?php
   $query = "SELECT * FROM tbl_product ORDER BY id ASC";
   $statement = $connect->prepare($query);
   $statement->execute();
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
   ?>
   <div class="col-md-3">
    <form method="post">
     <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">
      <img src="images/<?php echo $row["image"]; ?>" class="img-responsive" /><br />

      <h4 class="text-info"><?php echo $row["name"]; ?></h4>

      <h4 class="text-danger">$ <?php echo $row["price"]; ?></h4>

      <input type="text" name="quantity" value="1" class="form-control" />
      <input type="hidden" name="hidden_name" value="<?php echo $row["name"]; ?>" />
      <input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>" />
      <input type="hidden" name="hidden_id" value="<?php echo $row["id"]; ?>" />
      <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart" />
     </div>
    </form>
   </div>
   <?php
   }
   ?>
   
   
   <div style="clear:both"></div>
   <br />
   <h3>Order Details</h3>
   <div class="table-responsive">
   <?php echo $message; ?>
   <div align="right">
    <a href="index.php?action=clear"><b>Clear Cart</b></a>
   </div>
   <table class="table table-bordered">
    <tr>
     <th width="40%">Item Name</th>
     <th width="10%">Quantity</th>
     <th width="20%">Price</th>
     <th width="15%">Total</th>
     <th width="5%">Action</th>
    </tr>
   <?php
   if(isset($_COOKIE["shopping_cart"]))
   {
    $total = 0;
    $cookie_data = stripslashes($_COOKIE['shopping_cart']);
    $cart_data = json_decode($cookie_data, true);
    foreach($cart_data as $keys => $values)
    {
   ?>
    <tr>
     <td><?php echo $values["item_name"]; ?></td>
     <td><?php echo $values["item_quantity"]; ?></td>
     <td>$ <?php echo $values["item_price"]; ?></td>
     <td>$ <?php echo number_format($values["item_quantity"] * $values["item_price"], 2);?></td>
     <td><a href="index.php?action=delete&id=<?php echo $values["item_id"]; ?>"><span class="text-danger">Remove</span></a></td>
    </tr>
   <?php 
     $total = $total + ($values["item_quantity"] * $values["item_price"]);
    }
   ?>
    <tr>
     <td colspan="3" align="right">Total</td>
     <td align="right">$ <?php echo number_format($total, 2); ?></td>
     <td></td>
    </tr>
   <?php
   }
   else
   {
    echo '
    <tr>
     <td colspan="5" align="center">No Item in Cart</td>
    </tr>
    ';
   }
   ?>
   </table>
   </div>
  </div>
  <br />
 </body>
</html>





Saturday, 5 May 2018

AngularJS | Add Remove Input Fields Dynamically in PHP



In this post We would like to share you How can we implement add more and remove dynamic textbox or input fields by using AngularJS with PHP language. By using this sourcecode anybody can adding or removing form fields dynamically and after this save or insert that fields data into Mysql database by using PHP script. If you have not know How to dynamically add or remove HTML input fields by using Angular javascript then this tutorial is for you in which we have describe step by step How to use AngularJS code for make form with add or remove dynamic HTML input fields and after this we have describe how to save dynamic fields data by using PHP PDO.

If in our web project which we have build with AngularJS as frontend and in backend we have use PHP and in that we want to required add dynamic input fields then you have come on right place. Under this tutorial you can find full source code for add or remove input fields dynamically by using AngularJS and by using PHP with AngularJS we have insert that dynamic input fields data into mysql database. In this tutorial we have make following files.

  • index.html
  • database_connection.php
  • fetch_data.php
  • insert.php

So if you want to learn how to add or remove input fields dynamically in AngularJS with PHP. So you have to just follow this tutorial step by step.







index.php


First we have create simple index.html file in which we have already include bootstrap and AngularJS library. In this file we have write html code for display alert message by using bootstrap, create form with add or remove dynamic input fields and below form we have make on table for display inserted data. In this file we have also write Angular javascript code for fetch data from mysql table, add one more input fields, remove input fields and lastly we have make function for submit form data PHP script.


<!DOCTYPE html>
<html>
 <head>
  <title>AngularJS | Add Remove Input Fields Dynamically in PHP</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
 </head>
 <body>
  <br />
   <h3 align="center">AngularJS | Add Remove Input Fields Dynamically in PHP</h3>
  <br />
  <div ng-app="dynamicApp" ng-controller="dynamicController" class="container" style="width:600px;" ng-init="fetchData()">
   
   <div class="alert alert-success alert-dismissible" ng-show="success" >
    <a href="#" class="close" aria-label="close">&times;</a>
    {{successMessage}}
   </div>

   <div class="alert alert-danger alert-dismissible" ng-show="error" >
    <a href="#" class="close" aria-label="close">&times;</a>
    {{errorMessage}}
   </div>

   <form method="post" ng-submit="submitForm()">
    <div class="form-group">
     <label>Enter Your Name</label>
     <input type="text" name="name" id="name" ng-model="formData.person_name" class="form-control" />
    </div>
    <fieldset ng-repeat="row in rows">
     <div class="form-group">
      <label>Enter Your Programming Skill</label>
      <div class="row">
       <div class="col-md-9">
        <input type="text" name="programming_languages[]" class="form-control" ng-model="formData.skill[$index + 1]" />
       </div>
       <div class="col-md-3">
        <button type="button" name="remove" ng-model="row.remove" class="btn btn-danger btn-sm" ng-click="removeRow()"><span class="glyphicon glyphicon-minus"></span></button>
       </div>
      </div>
     </div>
    </fieldset>
    <div class="form-group">
     <button type="button" name="add_more" class="btn btn-success" ng-click="addRow()"><span class="glyphicon glyphicon-plus"></span> Add</button>
     <input type="submit" name="submit" class="btn btn-info" value="Save" />
    </div>
   </form>

   <div class="table-responsive">
    <table class="table table-bordered table-striped">
     <tr>
      <th>Name</th>
      <th>Programming Languages</th>
     </tr>
     <tr ng-repeat="name in namesData">
      <td>{{name.name}}</td>
      <td>{{name.programming_languages}}</td>
     </tr>
    </table>
   </div>
  </div>
 </body>
</html>

<script>

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

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

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

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

 $scope.rows = [{name: 'programming_languages[]', name: 'remove'}];

 $scope.addRow = function(){
  var id = $scope.rows.length + 1;
  $scope.rows.push({'id':'dynamic'+id});
 };

 $scope.removeRow = function(row){
  var index = $scope.rows.indexOf(row);
  $scope.rows.splice(index, 1);
 };

 $scope.formData = {};

 $scope.submitForm = function(){
  $http({
   method:"POST",
   url:"insert.php",
   data:$scope.formData
  }).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.formData = {};
    $scope.rows = [{name: 'programming_languages[]', name: 'remove'}];
    $scope.fetchData();
   }
  });
 };

});

</script>


fetch_data.php


After this we have make this file and it will fetch data from mysql database and send to angular javascript function.


<?php

//fetch_data.php

include('database_connection.php');

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

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

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

 echo json_encode($data);
}

?>


insert.php


This last file of this tutorial and under this file we have write PHP code for save or insert data into mysql database by using PHP with AngularJS.


<?php

//insert.php

include('database_connection.php');

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

$error = '';
$message = '';
$validation_error = '';
$name = '';
$programming_languages = '';

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

if(empty($form_data->skill))
{
 $error[] = 'Programming Language is Required';
}
else
{
 foreach($form_data->skill as $language)
 {
  $programming_languages .= $language . ', ';
 }
 $programming_languages = substr($programming_languages, 0, -2);
}

$data = array(
 ':name'      => $name,
 ':programming_languages' => $programming_languages
);

if(empty($error))
{
 $query = "
 INSERT INTO tbl_name 
 (name, programming_languages) VALUES 
 (:name, :programming_languages)
 ";
 $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);

?>

So, this is complete source code of Add or Remove input fields dynamically in AngularJS with PHP. If you want to get complete file of this tutorial then you can download by click on below link.