AngularJS For One Page Application With PHP MYSQL (Insert Data In DB)

AngularJS is a JavaScript framework having only JavaScript code. It is the best framework for those who want to make one page application. Like Voting Web Application, Lucky draw contestant etc. AngularJS extends the HTML tags properties with the ng-directives.

AngularJS is most optimized and easy framework for client side web page. Below is the google AngularJS API URL to use in our web pages.

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

Note: 1. Always use updated version of angular.min.js Google API.
Note: 2. Use data-ng- instead of ng- for HTML5 valid page.

Here, I will show some basic example of AngularJS with PHP code of my understanding, for more detail visit official website https://angularjs.org/

Following are the some important ng-directives we should know.

ng-app:  AngularJS application initialization. It is compulsory to declare scope of application. We can create multiple ng-app within a page. Example: <body ng-app="ngAppName"></body> OR <div ng-app="ngAppName"></div> OR <div ng-app="ngAppName2"></div><div ng-app="ngAppName3"></div>

ng-bind: This is same as innerHTML of html. We can assign value of any input field to html tags. Example: <p ng-bind="field name"></p> OR Use AngularJS expressions same as ng-bind. Example: <p>Addition: {{ 15 + 15 }}</p> OR <p>Name: {{ field name }}</p>

ng-init: This directive use to initialize the AngularJS application variables. Example: <div ng-app="ngAppName" ng-init="fname='pranaydac08'">

ng-model: It is pointed to the input field variable name which bind variable to this ng model.

ng-controller: AngularJS applications are manage by controllers. We can write multiple controllers in a ng-app. Example: <div ng-app="ngAppName" ng-controller="myController">

ng-repeat: This is use for repeatation of an HTML element like foreach(namesObject as fname). Example: <li ng-repeat="fname in namesObject">{{ fname }} </li>


AngularJS Example With PHP MYSQL (Insert Data In DB):

Step 1: Create DB & Table as below

CREATE DATABASE angularJS; 
CREATE TABLE users( `id` INT(11) NOT NULL AUTO_INCREMENT, `username` VARCHAR(250), `email` VARCHAR(250), PRIMARY KEY (`id`) );

Step 2: Create index.php file and copy below code there.

<!DOCTYPE html>
<html>

<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
    
<body ng-app="myApp">
<h2>AngularJS Example</h2>

<form ng-controller="myCotrollerName" name="myForm" novalidate>

<p ng-repeat="error in errors">* {{ error}} </p>   
<p ng-repeat="msg in msgs">* {{ msg}} </p>
  
<p>Username:<br>
<input type="text" name="username" ng-model="username" required placeholder="User Name">
<span style="color:red" ng-show="myForm.username.$dirty && myForm.username.$invalid">
<span ng-show="myForm.username.$error.required">Username is required.</span>
</span>
</p>

<p>Email:<br>
<input type="email" name="email" ng-model="email" required placeholder="Email">
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>

<p>
<!--<input type="button" ng-click='SignUp();' ng-disabled="myForm.username.$dirty && myForm.username.$invalid ||  myForm.email.$dirty && myForm.email.$invalid" value="Submit"/>-->
<button ng-click='SignUp();'>Submit</button>
</p>

</form>

<script>
var myApp = angular.module("myApp", []); 
myApp.controller("myCotrollerName", function($scope, $http) {
    $scope.username = 'pranaydac08';
    $scope.email = 'pranaydac.test@gmail.com';
$scope.errors = [];
$scope.msgs = [];

$scope.SignUp = function() {

$scope.errors.splice(0, $scope.errors.length); // blank all error messages
$scope.msgs.splice(0, $scope.msgs.length);// blank all messages

// http post call to save_info.php file to save data in db
$http.post('save_info.php', {'username': $scope.username, 'email': $scope.email}
).success(function(data, status, headers, config) {
if (data.msg != '')
{
$scope.msgs.push(data.msg);
}
else
{
$scope.errors.push(data.error);
}
}).error(function(data, status) { 
$scope.errors.push(status);
});
}
}); 

</script>


</body>
</html>


Step 3: Create save_info.php file and copy below code there. This code will save data into database.

<?php
//Get the data from http request 
$data = json_decode(file_get_contents("php://input"));
$username = mysql_real_escape_string($data->username); // Use mysql_real_escape_string to prevent data from sql injection.
$email = mysql_real_escape_string($data->email);
 
/* DB Connection @ localhost  */
$db_hostname = 'localhost';
$db_userName = 'root';
$db_password = '';
$db_name = 'angularJS';

$con = mysql_connect($db_hostname, $db_userName, $db_password);
mysql_select_db($db_name, $con);
 
$query = 'select count(*) as cnt from users where email ="' . $email . '"';
$query_res = mysql_query($query);
$res = mysql_fetch_assoc($query_res);
 
if ($res['cnt'] == 0) {
$query_ins = 'INSERT INTO users (username,email) values ("' . $username . '","' . $email . '")';
$query_ins_res = mysql_query($query_ins);
if ($query_ins_res) {
$arr = array('msg' => "User Added Successfully!!!", 'error' => '');
$jsn_data = json_encode($arr);
print_r($jsn_data);
} else {
$arr = array('msg' => "", 'error' => 'Error In inserting user data');
$jsn_data = json_encode($arr);
print_r($jsn_data);
}
} else {
$arr = array('msg' => "", 'error' => 'User Already exists!');
$jsn_data = json_encode($arr);
print_r($jsn_data);
}
?>

Step 4: Done. Please comments, if having any issue.
AngularJS For One Page Application With PHP MYSQL (Insert Data In DB) AngularJS For One Page Application With PHP MYSQL (Insert Data In DB) Reviewed by Pranay Gondane on 3:29:00 AM Rating: 5

No comments

Free! Free!Free! Subscribe to Get Free PHP (Magento) tutorial Update in Your Inbox!!! Hurry Up!!!