angularjs insert update delete example in php

Rate this post

angularjs insert update delete example in php

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.

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.







AngularJS Insert Update Delete Using PHP MySQL - https://www.yttags.com/


















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.

AngularJS Insert Update Delete Using PHP MySQL - yttags

AngularJS Insert Update Delete Using PHP MySQL - yttags

# Name Email Company Name Designation Action
1 vetri support[at]yttags yttags Director Edit | Delete

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.


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.

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`);

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.


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.

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 yttags.

See also  Angular Input Keypress Event Example - keypress event in angular

Hi, I’m Jaydip Gondaliya. I help build websites, grow businesses, big and small. If that is what you want, contact me. I’m currently available for freelance work. info@yttags.com

Leave a Comment