AngularJS Insert Update Delete using php mysql

AngularJS Insert Update Delete using php mysql

In this post we will show you AngularJS Insert Update Delete using php mysql, hear for AngularJS Insert Update Delete using php mysql we will give you demo and example for implement.

Angularjs is a best structure to build up the single page application. You have play out this operation (Insert, Update, Delete) in single page without reviving for AngularJS Insert Update Delete using php mysql. So every clients resemble to execute the AngularJS application. Presently we are create Insert, Update, Delete Using PHP and MySQL in AngularJS structure.

Read More Demo Download

HTML Form and Bootstrap Design

To create responsive layout for this post of AngularJS Insert Update Delete using php mysql, we using Twitter Bootstrap. For this first create post directory in we server root folder (htdocs/www). Now create index.html file and add the following html basic markup in it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AngularJS Insert Update Delete Using PHP MySQL - onlinecode</title>
<!-- Add Bootstrap -->
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300,200' rel='stylesheet' type='text/css'>
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/animate.min.css" rel="stylesheet">

<!-- add Script -->
<!-- add jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- add and Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="js/angular-custom.js"></script>
<script src="js/angular.min.js"></script>
</head>
<body>
</body>
</html>

Now using Bootstrap Grid system I have split into two column. One for display HMTL form and other for to display saved details. Here is the HTML form markup.


<div class="container">
<h2 class="title text-center">AngularJS Insert Update Delete Using PHP MySQL - onlinecode</h2>

<div class="row mt80">
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 animated fadeInDown divcls">
<div class="alert adivcls lert-danger text-center alert-failure-div" role="alert" style="display: none">
</div>
<div class="alert divcls alert-success text-center alert-success-div" role="alert" style="display: none">
</div>
<!-- user form -->
<form novalidate name="userForm">
<div class="form-group divcls">
<label for="name">Name</label>
<input type="text" class="form-control divcls" id="name" name="name" placeholder="Add Name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control divcls" id="email" name="email" placeholder="Add Email">
</div>
<div class="form-group">
<label for="company_name">Company Name</label>
<input type="text" class="form-control divcls" id="company_name" name="company_name" placeholder="Add Company Name">
</div>
<div class="form-group">
<label for="designation">Designation</label>
<input class="form-control divcls" id="designation" name="designation" placeholder="Add Designation">
</div>
<div class="text-center">
<button data-loading-text="Saving User........" type="submit" class="btn btn-save">Save User Data</button>
</div>
</form>
</div>
<div class="col-xs-12 col-sm-8 divcls col-md-8 col-lg-8 animated fadeInUp">
<h2 class="title text-center">AngularJS Insert Update Delete Using PHP MySQL - onlinecode</h2>
<div class="table-responsive divcls">
<table class="table divcls table-bordered table-hover table-striped">
<thead>
<tr>
<th width="5%">#</th>
<th width="19%">Name</th>
<th width="19%">Email</th>
<th width="15%">Company Name</th>
<th width="24%">Designation</th>
<th width="18%">Action</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>vetri</td>
<td>support[at]onlinecode</td>
<td>onlinecode</td>
<td>Director</td>
<td><span> Edit</span> | <span>Delete</span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>

Read More Demo Download

Create AngularJS Module:

AngularJS is MVC structured JavaScript framework. It allow us to do shopper facet work flat out, additionally it reduces server load.

When we opt for any framework, it’s following benefits.

  • We can write manageable code.
  • We can write manageable code.
  • We attempt to follow that framework style pattern and writing structure.
  • It facilitate United States to end task thus quickly.

In AngularJS everything is within the module. The module is like instrumentality it’ll have all codes we have a tendency to write for this explicit AngularJS application. Then if our module needs some additional practicality then we are going to inject explicit module in our AngularJS application victimisation dependency Injection. This avoids excess script loading and additionally improves performance of the applying.

Here is the syntax to create AngularJS module. we creating ‘postDataModule’ for this application.

$postDataModule = angular.module('postDataModule', []);

Now apply that crated AngularJS application to HTML DOM using ng-app directive. You may apply this wherever you like to add in your HTML document. we adding that module in the body tag like this.

<body data-ng-app="postDataModule">

When AngularJS compiler encounters this directive then it initialize AngularJS application.
Now Create AngularJS controller. Here is the syntax for creating controller.

$postDataModule.controller('PostDataController',function($scope, $http));

It requires name of the controller (i.e. PostDataController ), followed by anonymous function. By default all the AngularJS Controller will inject $scope service. All the Controller will pass the data from model to view via this $scope service. Here the Controller is like a linker between Model and read.

Read More Demo Download

Configuration of AngularJS modules and scripts

Here our whole AngularJS application script for AngularJS Insert Update Delete Using PHP MySQL.

$postDataModule = angular.module('postDataModule', []);
var base_path = document.getElementById('base_path').value;
$postDataModule.controller('PostDataController',function($scope, $http){
$scope.post = {};
$scope.tempUser = {};
$scope.post.users = [];
$scope.index = '';
$scope.editMode = false;

var siteurl = base_path+'ajax.php';

$scope.saveUser = function(){
$http({
url: siteurl,
method: 'post',
data: $.param({'user' : $scope.tempUser, 'type' : 'save_user_data' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success(function(data, status, headers, config) {
if(data.success){
if( $scope.editMode ){
// execute output data
$scope.post.users[$scope.index].id = data.id;
$scope.post.users[$scope.index].email = $scope.tempUser.email;
$scope.post.users[$scope.index].name = $scope.tempUser.name;
$scope.post.users[$scope.index].designation = $scope.tempUser.designation;
$scope.post.users[$scope.index].companyName = $scope.tempUser.companyName;
}else{
$scope.post.users.push({
id : data.id,
email : $scope.tempUser.email,
name : $scope.tempUser.name,
designation : $scope.tempUser.designation,
companyName : $scope.tempUser.companyName
});
}
$scope.messageSuccess(data.message);
$scope.userForm.$setPristine();
$scope.tempUser = {};

}else{
$scope.messageFailure(data.message);
}
}).
error(function(data, status, headers, config) {
//$scope.codeStatus = response || "Request failed";
});

jQuery('.btn-save').button('reset');
}

$scope.addUser = function(){

jQuery('.btn-save').button('loading');
$scope.saveUser();
$scope.editMode = false;
$scope.index = '';
}

$scope.updateUser = function(){
$('.btn-save').button('loading');
$scope.saveUser();
}

$scope.editUser = function(user){
$scope.tempUser = {
id: user.id,
email : user.email,
name : user.name,
designation : user.designation,
companyName : user.companyName,
};
$scope.editMode = true;
$scope.index = $scope.post.users.indexOf(user);
}

$scope.deleteUser = function(user){
var r = confirm("Are you sure want to delete this user!");
if (r == true) {
$http({
method: 'post',
url: siteurl,
data: $.param({ 'id' : user.id, 'type' : 'delete_user_data' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success(function(data, status, headers, config) {
if(data.success){
// execute output data
var indexdata = $scope.post.users.indexOf(user);
$scope.post.users.splice(indexdata, 1);
}else{
$scope.messageFailure(data.message);
}
}).
error(function(data, status, headers, config) {
//$scope.messageFailure(data.message);
});
}
}
// call show message
$scope.init = function(){
$http({
url: siteurl,
method: 'post',
data: $.param({ 'type' : 'get_Users_Data' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success(function(data, status, headers, config) {
if(data.success && !angular.isUndefined(data.data) ){
// execute output data
$scope.post.users = data.data;
}else{
// show message
$scope.messageFailure(data.message);
}
}).
error(function(data, status, headers, config) {
//$scope.messageFailure(data.message);
});
}
// show message
$scope.messageFailure = function (msgs){
jQuery('.alert-failure-div > p').html(msgs);
jQuery('.alert-failure-div').show();
jQuery('.alert-failure-div').delay(5000).slideUp(function(){
jQuery('.alert-failure-div > p').html('');
});
}
// show message
$scope.messageSuccess = function (msgs){
jQuery('.alert-success-div > p').html(msgs);
jQuery('.alert-success-div').show();
jQuery('.alert-success-div').delay(5000).slideUp(function(){
jQuery('.alert-success-div > p').html('');
});
}

$scope.getError = function(error, name){
if(angular.isDefined(error)){
if(error.required && name == 'name'){
return "Please enter your name";
}else if(error.email && name == 'email'){
return "Please enter valid email";
}else if(error.required && name == 'email'){
return "Please enter your email";
}else if(error.required && name == 'company_name'){
return "Please enter your company name";
}else if(error.required && name == 'designation'){
return "Please enter valid designation";
}else if(error.minlength && name == 'company_name'){
return "Company name must be 3 characters long";
}else if(error.minlength && name == 'name'){
return "Name must be 3 characters long";
}else if(error.minlength && name == 'designation'){
return "Designation must be 3 characters long";
}
}
}

});

Create sample MySQL Database & Table

Use the following SQL queries to create sample table for this application for AngularJS Insert Update Delete Using PHP MySQL.

CREATE TABLE IF NOT EXISTS `employee` (
`id` int(15) NOT NULL,
`email` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`designation` varchar(255) NOT NULL,
`companyName` varchar(255) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

ALTER TABLE `employee`
ADD PRIMARY KEY (`id`);

Read More Demo Download

PHP web service for AngularJS CRUD operation:

First create config.php file and define site wide constants in it for AngularJS Insert Update Delete Using PHP MySQL.

<body data-ng<?php

//site specific configuration declartion
define( 'BASE_PATH', 'http://localhost/post/');
define('DB_HOST', 'localhost');
define('DB_USERNAME','root');
define('DB_NAME', 'post');
define('DB_PASSWORD','');

$mysqli_conn  = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
echo("connect Failed, error message is : ". mysqli_connect_error());
exit();
}-app="postDataModule">

Create AngularJS CRUD Code for Ajax

Now create ajax.php file that handles all the Ajax request from AngularJS for Insert, Read, Update and Delete operation. Here is the full PHP script that handles the CRUD operation for AngularJS Insert Update Delete Using PHP MySQL.


<?php

require_once 'config.php';

if( isset($_POST['type']) && !empty( isset($_POST['type']) ) ){
$type = $_POST['type'];

switch ($type) {
case "save_user_data":
save_user_data($mysqli_conn);
break;
case "delete_user_data":
delete_user_data($mysqli_conn, $_POST['id']);
break;
case "get_Users_Data":
get_Users_Data($mysqli_conn);
break;
default:
invalid_Request_data();
}
}else{
invalid_Request_data();
}

/**
* This function will handle user add, update functionality
* @throws Exception
*/
function save_user_data($mysqli_conn){
try{
$employeedata = array();
$get_name = $mysqli_conn->real_escape_string(isset( $_POST['user']['name'] ) ? $_POST['user']['name'] : '');
$get_companyName = $mysqli_conn->real_escape_string(isset( $_POST['user']['companyName'] ) ? $_POST['user']['companyName'] : '');
$get_designation = $mysqli_conn->real_escape_string( isset( $_POST['user']['designation'] ) ? $_POST['user']['designation'] : '');
$get_email = $mysqli_conn->real_escape_string( isset( $_POST['user']['email'] ) ? $_POST['user']['email'] : '');
$id = $mysqli_conn->real_escape_string( isset( $_POST['user']['id'] ) ? $_POST['user']['id'] : '');

if($get_name == '' || $get_companyName == '' || $get_designation == ''|| $get_email == '' ){
throw new Exception( "Required fields missing, Please enter and submit" );
}

if(empty($id)){
$query = "INSERT INTO employee (`id`, `name`, email, `companyName`, `designation`) VALUES (NULL, '$get_name', '$get_email', '$get_companyName', '$designation')";
}else{
$query = "UPDATE employee SET `name` = '$get_name', email = '$get_email', `companyName` = '$get_companyName', `designation` = '$get_designation' WHERE `employee`.`id` = $id";
}

if( $mysqli_conn->query( $query ) ){
$employeedata['success'] = true;
if(!empty($id))$employeedata['message'] = 'User updated successfully.';
else $employeedata['message'] = 'User inserted successfully.';
if(empty($id))$employeedata['id'] = (int) $mysqli_conn->insert_id;
else $employeedata['id'] = (int) $id;
}else{
throw new Exception( $mysqli_conn->sqlstate.' - '. $mysqli_conn->error );
}
$mysqli_conn->close();
echo json_encode($employeedata);
exit;
}catch (Exception $e){
$employeedata = array();
$employeedata['success'] = false;
$employeedata['message'] = $e->getMessage();
echo json_encode($employeedata);
exit;
}
}

/**
* This function will handle user/employee deletion
* @param string $id
* @throws Exception
*/
function delete_user_data($mysqli_conn, $id = ''){
try{
$employeedata = array();
if(empty($id)) throw new Exception( "Invalid User Data." );
$employee_query = "DELETE FROM `employee` WHERE `id` = $id";
if($mysqli_conn->query( $employee_query )){
$employeedata['success'] = true;
$employeedata['message'] = 'User hass been deleted successfully.';
echo json_encode($employeedata);
exit;
}else{
throw new Exception( $mysqli_conn->sqlstate.' - '. $mysqli_conn->error );
}

}catch (Exception $e){
$employeedata = array();
$employeedata['success'] = false;
$employeedata['message'] = $e->getMessage();
echo json_encode($employeedata);
exit;
}
}

/**
* This function gets list of users/employee from database
*/
function get_Users_Data($mysqli_conn){
try{

$get_query = "SELECT * FROM `employee` order by id desc limit 10";
$get_result = $mysqli_conn->query( $get_query );
$employeedata = array();
while ($row_val = $get_result->fetch_assoc()) {
$row_val['id'] = (int) $row_val['id'];
$employeedata['data'][] = $row_val;
}
$employeedata['success'] = true;
echo json_encode($employeedata);
exit;

}catch (Exception $e){
$employeedata = array();
$employeedata['success'] = false;
$employeedata['message'] = $e->getMessage();
echo json_encode($employeedata);
exit;
}
}

function invalid_Request_data()
{
$request_data = array();
$request_data['success'] = false;
$request_data['message'] = "Request is Invalid.";
echo json_encode($request_data);
exit;
}

Read More Demo Download

Hope this code and post will helped you for implement AngularJS Insert Update Delete using php mysql. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve onlincode. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs onlincode.org

Reference @ vetbossel.in

Leave a Comment

Your email address will not be published. Required fields are marked *

78  +    =  87

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US