Ajax with AngularJS and PHP MySQLi – Angular CRUD

Ajax with AngularJS and PHP MySQLi – Angular CRUD

In this Post We Will Explain About is Ajax with AngularJS and PHP MySQLi – Angular CRUD With Example and Demo.Welcome on Live24u.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to AngularJS CRUD Operation With PHP/MySQLi Example

In this post we will show you Best way to implement AngularJS CRUD Example Using PHP MySQLi Database, hear for AngularJS PHP MySQLi CRUD (Create, Read, Update, Delete) Operations with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.




The Angular $http service

The $http service is what we use in Angular applications to perform Ajax calls. In order to use the service we first need to inject it as a dependency to the controller.

<script>
var liveajaxDemo = angular.module('liveajaxDemo', []);

liveajaxDemo.controller('cuestomliveCtrl', function($scope, $http){

});   
</script>

For example : api/do_fetch.php

//angularjs insert update delete using php MySQLi
$http({
   method: 'GET',
   url: 'api/do_fetch.php'
}).then(function (liveResults) {
   //source code to run in case of success
}, function (liveResults) {
   //source code to run in case of error
});

The HTML(index.html)

Every list item contains a emplr’s name and mobile number and a button for deleting the emplr with the ‘removeEmployer’ function.

Also Read :   vuejs http get and post methods example | Fetching and persisting data using vue.js

<!doctype html>
<html ng-app="liveajaxDemo">
<head lang="en">
    <meta charset="utf-8">
    <title>Simple Angular Ajax with PHP MySQLi Example</title>
</head>
<body>

<h2>The form</h2>

<div ng-controller="cuestomliveCtrl"

    <form> 
        <p>Fill the HTML form using Angular</p>
        <div>
            <label>client Name</label>
            <input type="text" ng-model="empCnameNew">
        </div>
            
        <div>
            <label>Phone</label>
            <input type="text" ng-model="empCphoneNew">
        </div>
    
        <input type="button" value="Add" ng-click="addEmployer()">
        
    </form>
    
    <h2>The Empoyer list</h2>
    <p>The all names that were inserted with the HTML form.</p>
    
    <ul>
        <li ng-repeat="emplr in employer">
            <button ng-click="removeEmployer( emplr.id )">Delete</button> {{ emplr.name }} {{ emplr.mobile }}
        </li>
    </ul>

</div>

<script src="live24u/libs/angular-1.4.9.min.js"></script>
<script src="live24u/assets/js/app.js"></script>

</body>
</html>

The Angular code(app.js)

We Below the AngularJS source code in the file path Like as ‘live24uassets/js/app.js’.

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

liveajaxDemo.controller('cuestomliveCtrl',function($scope,$http){
    $scope.employer;

    $scope.fetchEmployer = function() {
          $http({              
              method: 'GET',
              url: '/api/do_fetch.php'              
          }).then(function (liveResults) {              
              // simple on success
              $scope.employer = liveResults.data;
              
          }, function (liveResults) {              
              //simple on error
              console.log(liveResults.data,liveResults.status);              
          });
    };

    $scope.addEmployer = function() {
          $http({              
               method: 'POST',
               url:  '/api/empPost.php',
               data: {empCnameNew: $scope.empCnameNew, empCphoneNew: $scope.empCphoneNew }
               
          }).then(function (liveResults) {// on success            
               $scope.fetchEmployer();            
          }, function (liveResults) {              
               console.log(liveResults.data,liveResults.status);               
          });
    };
    $scope.removeEmployer = function( id ) {
          $http({              
              method: 'POST',
              url:  '/api/delete.php',
              data: { recordId : id }              
          }).then(function (liveResults) {        
              $scope.fetchEmployer();        
          }, function (liveResults) {              
              console.log(liveResults.data,liveResults.status);              
          });
        };

        $scope.fetchEmployer();
});

The database

We store or save simple the dump data that we fetch with the HTML form in a employer table.

Also Read :   Restful insert update edit delete using Angularjs and PHP

//AngularJS CRUD Operation With PHP/MySQLi
CREATE TABLE IF NOT EXISTS `employer` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) DEFAULT NULL,
  `mobile` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

The PHP

The PHP server side backend side will be in the make a folder like as ‘api/’ Path, as well as it has the simple server side following 4 scripts:

api/connect.php 
api/do_fetch.php 
api/empPost.php 
api/delete.php

connect.php

<?php
//AngularJS CRUD Operation With PHP/MySQLi  db credentials
define('DB_HOST', 'YOUR_HOST_NAME');
define('DB_USER','YOUR_USER_NAME');
define('DB_PASS','');
define('DB_NAME','YOUR_DATABASE_NAME');

// Connect with the database.
function connect()
{
  $connect = mysqli_connect(DB_HOST ,DB_USER ,DB_PASS ,DB_NAME);
  if (mysqli_connect_errno($connect))
  {
    die("Sorry Failed to database connect:" . mysqli_connect_error());
  }
  mysqli_set_charset($connect, "utf8");
  return $connect;
}

do_fetch.php

simple in this file do_fetch.php to read or fetch from the mysql database

<?php
require 'connect.php';
$connect = connect();

//AngularJS CRUD Operation With PHP/MySQLi Get the data
$employer = array();
$sql = "SELECT id, name, mobile FROM employer";

if($empresult = mysqli_query($connect,$sql))
{
  $count = mysqli_num_rows($empresult);

  $gst = 0;
  while($drow = mysqli_fetch_assoc($empresult))
  {
      $employer[$gst]['id']    = $drow['id'];
      $employer[$gst]['name']  = $drow['name'];
      $employer[$gst]['mobile'] = $drow['mobile'];

      $gst++;
  }
}

$json = json_encode($employer);
echo $json;
exit;

empPost.php

in this server sdei empPost.php to add or insert new some users records to the store in mysql database

Also Read :   vuejs insert update delete Example - Vue.js CRUD

<?php
require 'connect.php';

$connect = connect();

//AngularJS CRUD Operation With PHP/MySQLi Add the new data to the database.
$livefetchdatapost = file_get_contents("php://input");
if(isset($livefetchdatapost) && !empty($livefetchdatapost))
{
    $dtarequest     = json_decode($livefetchdatapost);
    
    $empCnameNew  = preg_replace('/[^a-zA-Z ]/','',$dtarequest->empCnameNew);
    $empCphoneNew = preg_replace('/[^0-9 ]/','',$dtarequest->empCphoneNew);
    
    if($empCnameNew  == '' || $empCphoneNew == '') return;

    $sqlquery = "INSERT INTO `employer`(`name`, `mobile`) VALUES ('$empCnameNew','$empCphoneNew')";

    mysqli_query($connect,$sqlquery);
}
exit;

delete.php

Remove a data record from the mysql database.

<?php
require 'connect.php';

$connect = connect();

//AngularJS CRUD Operation With PHP/MySQLi Delete record by id.
$livefetchdatapost = file_get_contents("php://input");
if(isset($livefetchdatapost) && !empty($livefetchdatapost))
{
    $datareq = json_decode($livefetchdatapost);

    $id  = (int)$datareq->recordId;

    $lstsql = "DELETE FROM `employer` WHERE `id` = '$id' LIMIT 1";

    mysqli_query($connect,$lstsql);
}

You are Most welcome in my youtube Channel Please subscribe my channel. and give me FeedBack.
More Details……
Angularjs Example





Example

I hope you have Got What is AngularJS CRUD Operation With PHP/MySQLi And how it works.I would Like to have FeedBack From My Blog(live24u.com) readers.Your Valuable FeedBack,Any Question,or any Comments about This Article(live24u.com) Are Most Always Welcome.