Insert data into database using AngularJS and PHP!

angular-data

In this post, we are going to see how we can fetch from and insert data into MySQL database using AngularJS and PHP.

I am using PHP mysqli to insert records into the database. This tutorial is more concentrated on AngularJS than PHP, so basically for experienced PHP developers.

Let’s see index.html:

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
  <title>Angular & PHP Tutorial</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <!--angular js cdn-->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <script src="https://code.angularjs.org/1.6.4/angular-route.min.js"></script>

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  
  <!--our code-->
  <script src="js/app.js"></script>
  <script src="js/controller.js"></script>
</head>
<body>
  <div class="container">
    <h2 style="font-style: italic; color: darkblue;">Angular & PHP - Theonlytutorials.com</h2>
    <hr></hr>
    <div class="main" ng-view></div>
  </div>
  <br />
</body>
</html>

The above code is just a normal HTML page with some extra attributes such as ng-app=”myApp” and ng-view, these are called AngularJS Directives. 

Also note, I have included angular-route.min.js in my application, which helps to create Single Page Application.

Now, let’s see the app.js code, so I can explain the above Directives ng-app=”myApp”:

var myApp = angular.module('myApp',[
  'ngRoute',
  'studentModule'
]);

myApp.config(['$routeProvider', function($routeProvider){
  $routeProvider.
  when('/', {
    templateUrl: 'view/list.html',
    controller: 'ListController'
  }).
  when('/add', {
    templateUrl: 'view/add.html',
    controller: 'AddController'
  }).
  otherwise({
    redirectTo: '/'
  });
}]);

In the above code, we have created a new app called “myApp” using the AngularJS Module API. So basically ng-app=”myApp” is a reference to this module.

The ngRoute is the Angular Routing module to build a Single Page Application.
studentModule is our custom module.
then the $routeProvider helps to configure the routes.

Inside the $routeProvider configuration, you can see there are two more files (list.html and add.html). These are the other view files which are going to load when you visit (/) and (/add), those are here:

list.html:

<h3 style="font-weight: bold;">Students List</h3>
<table class="table table-bordered">
  <thead>
  <tr>
    <th>Student ID</th><th>Student Name</th><th>Student Email</th>
  </tr>
  </thead>
  <tbody>
    <tr ng-repeat="item in studentList">
      <td>{{item.student_id}}</td><td>{{item.student_name}}</td><td>{{item.student_email}}</td>
    </tr>
  </tbody>
</table>

<a href="#!add" class="btn btn-warning">Add Student</button>


add.html:

<h3 style="font-weight: bold;">Add a Student</h3>
<form name="form" ng-submit="add_student(student_name, student_email)">
  <div class="alert alert-success" ng-show="msg">
    <strong>Success!</strong> User Added!.
  </div>
  <div class="form-group">
    <label for="student_name">Name</label>
    <input class="form-control" type="text" name="student_name" ng-model="student_name" required />
  </div>
  
  <div class="form-group">
    <label for="student_name">Email</label>
    <input class="form-control" type="email" name="student_email" ng-model="student_email" required />
  </div>
</div>
<br />
<button type="submit" class="btn btn-primary" >Submit</button>
<a href="#" class="btn btn-warning" >Go Back</button>
</form>

Let’s see the controller.js:

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

studentModule.controller('ListController', ['$scope', '$http', function($scope, $http){
  //use $http.get() to get the list of students 
  $http.get('php/student_list.php').then(function(response){
    //send back the student data to the list.html view
    $scope.studentList = response.data;
  });
}]);

studentModule.controller('AddController', ['$scope', '$http', '$timeout', function($scope, $http, $timeout){
  
  //create a function add_student with params name and email
  $scope.add_student = function (name, email){
    //set the data array
    var data = {
      name: name,
      email: email
    }
    
    //use $http.post to send above data to php
    
    $http.post('php/add_student.php', JSON.stringify(data)).then(function(response){
      //clear the form fields
      $scope.student_name = "";
      $scope.student_email = "";
      
      //show success msg
      $scope.msg = true;
      //hide the msg after 2 secs
      $timeout(function(){$scope.msg = false;}, 1000);
    });
  }
  
}]);

Controllers in AngularJS controls the data, basically used to do the business logic.

There are two controllers in our application,

i. ListController – this lists the student records from the database.
ii. AddController – this adds the student record to the database.

Read the in-line comment in the above script to understand.

And finally the PHP files are here: 

student_list.php

<?php 
require('config.php');

$query = mysqli_query($con, 'select * from students');

$student_list = array();
while($rows = mysqli_fetch_assoc($query)){
  $student_list[] = $rows;
}

print json_encode($student_list);

add_student.php

<?php
require('config.php');

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

$name = mysqli_real_escape_string($con, $data->name);
$email = mysqli_real_escape_string($con, $data->email);

$query = mysqli_query($con, "insert into students (student_name, student_email) values ('$name', '$email')") or die ('Unable to execute query. '. mysqli_error($con));

config.php

<?php 

$con = mysqli_connect('dbhost', 'dbuser', 'dbpass');
$db = mysqli_select_db($con, 'dbname');

Table structure:

--
-- Table structure for table `students`
--

CREATE TABLE `students` (
  `student_id` int(10) UNSIGNED primary key auto_increment NOT NULL,
  `student_name` varchar(50) DEFAULT NULL,
  `student_email` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `students`
--

INSERT INTO `students` (`student_id`, `student_name`, `student_email`) VALUES
(1, 'agurchand', 'agurchand@agurchand.com');

 

See the demo here or you can just download it:

demodownload

 

 

 

One thought on “Insert data into database using AngularJS and PHP!

Leave a Reply

Theme: Overlay by Kaira
Agurchand