AngularJS with PHP Server

AngularJS with PHP is a front-end javascript framework. php a programming language to make dynamic and database driven web sites.

AngularJS With PHP is very powerful when it comes to interactive HTML5 and model binding. On the other hand, PHP fenable quick, well-structured, safe and powerful web application development. Both technologies provide sophisticated means for data access, iteration and page layouting.

AngularJS page can communicate with the server via REST services to get data instead of retrieving it from for example PHP variables directly.

In AngularJS With PHP, we use the $http service that makes working Like AJAX.

In this Blog we create simple demo for post form data on php serve and get data using AngularJS With PHP.

we are going to develop a book list application that can store book’s name, book’s price and book’s created date. The application enables us to add, read and delete the records. The server side is written in PHP.

First we crete html form as below to submit and save to database.

HTML Page – Index.html

<!doctype html>
<html ng-app="phpApp">
<head lang="en">
<meta charset="utf-8">
<title>Angular js post data on php server</title>
</head>
<body>
<h2>The form</h2>
<div ng-controller="bookController"
     <form> 
	<p>Add Book</p>
	<div>
	<label>Book Name</label>
	<input type="text" ng-model="bookName">
        </div>
	<div>
	<label>Book Price</label>
	<input type="text" ng-model="bookPrice">
	</div>
	<div>
	<label>Book Author</label>
	<input type="text" ng-model="bookAuthor">
	</div>
    <input type="button" value="Add Book" ng-click="addBook()">
    </form>
    <h2>The Book list</h2>
    <ul>
      <li ng-repeat="books in book">
      {{ book.book_name }} | {{ book.book_price}} |  {{ book.book_author }}
      </li>
    </ul>
</div>
<script src="/libs/angular-1.4.9.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>

In above code we include 2 js files; one is Angularjs library and another one app.js which we will be using in writing controller of our form.

On First part We define the application by using ng-app on the html tag. The name of the application is phpApp.

We define Controller of our form on div which wrapper form tags is ng- controller =bookController.

On submit button we put ng-click = addBook() on clicking on this button submit book data.

On second part of above code display book list. In this ng-repeat display all record of book.

Now we, create app.js file in js directory

app.js

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

app.controller('bookController',function($scope,$http){
      $scope.books;
      $scope.getBook = function() {
	$scope.url=get.php;
        $http.get($scope.url).
        success(function(response) {
        $scope.books = response;
        });
        };
	 $scope.addBook = function() {
	 $scope.url=post.php;
         $http.post($scope.url, {"book_name": $scope.bookName, "book_price": $scope.bookPrice, "book_author": $scope.bookAuthor}).
         success(function(response) {
         $scope.getBook();
          });
        };
    });

In above code First we define module application as “phpApp”.

After this we define our controller ‘bookController’ with two dependency ‘$scope’ and ‘$http’.

For current scope we use $scope.

$http is service is what we use in angular applications to perform Ajax calls.

Next, we define addBook function and post data on url define in $scope.url And in there success call getbook function and get all book record.

Now we create database table for books Like this

CREATE TABLE IF NOT EXISTS `books` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `book_name` varchar(60) DEFAULT NULL,
  `book_price` float(8,2) DEFAULT NULL,
  `book_author` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

Next we create dbconnect.php file for connectivity with database like this,

dbconnect.php

<?php
define('DB_HOST', 'localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','phpangular');
function connect()
{
  $connect = mysqli_connect(DB_HOST ,DB_USER ,DB_PASS ,DB_NAME);
  if (mysqli_connect_errno($connect))
  {
    die("Failed to connect:" . mysqli_connect_error());
  }
  mysqli_set_charset($connect, "utf8");
  return $connect;
}

Next we create post.php file insert book record in database

post.php

<?php
require 'dbconnect.php';

$connect = connect();

$bookdata = file_get_contents("php://input");
if(isset($bookdata) && !empty($bookdata))
{
    $request     = json_decode($bookdata);
    
    $bookname  = $request->book_name;
    $bookprice = $request->book_price;
    $bookauthor = $request->book_author;
  $sql = "INSERT INTO `books`('book_name', 'book_price,'book_author') VALUES ('$bookname','$bookprice','$bookauthor')";

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

In above code we get posted form data in the following code
file_get_contents(“php://input”);

The data need to json decoded as we seen above code.

At last we create get.php file for fetch all book records data in json format.

get.php

<?php
require 'dbconnect.php';
$connect = connect();
// Get the data
$book = array();
$sql = "SELECT * FROM books";
if($result = mysqli_query($connect,$sql))
{
  $count = mysqli_num_rows($result);
  $i = 0;
  while($row = mysqli_fetch_assoc($result))
  {
      $book[$i]['id']    = $row['id'];
      $book[$i]['book_name']  = $row['book_name'];
      $book[$i]['book_price'] = $row['book_price'];
      $book[$i]['book_author'] = $row['book_author'];
      $i++;
  }
}
$json = json_encode($book);
echo $json;
exit;

In above code we pass data as json_encode() format.