Angular JS CRUD

 
AngularJS is a JavaScript Framework and it is a library written in JavaScript. AngularJS can be added to a web page using a <script> tag. AngularJS extends HTML attributes with Directives. AngularJS Directives are HTML attributes with a "ng" prefix (ng-init). If you are a beginner to AngularJS and looking for working example on AngularJs, this tutorial will help you a lot. This tutorial will focus on CRUD (Create, Read, Update, and Delete) operations with AngularJS. We’ll do the view, add, edit, and delete operations on a single page using AngularJS with PHP and MySQL.

In this example AngularJS CRUD application, we’ll implement the following functionalities.

Fetch the users data from the database using PHP & MySQL, and display the users data using AngularJS.
Add user data to the database using AngularJS, PHP, and MySQL.
Edit and update user data using AngularJS, PHP, and MySQL.
Delete user data from the database using AngularJS, PHP, and MySQL.
All the CRUD operations (view, add, edit, delete) will be done on a single page and without page reload or refresh. In front-end part mainly AngularJs will handle the whole process and little jQuery will be used for some cases. In the back-end, PHP will communicate with the database and provide the respective requested data to the front-end. PDO extension and MySQL will help to connect with the database and database-related operations (select, insert, update, and delete).

Before you begin to AngularJS CRUD example, take a look at the files structure of the application which are going to build.

angularjs-crud-operations-php-mysql-files-structure-codexworld
Database Table Creation
For this example application, we’ll create a simple table (users) with some basic columns where users data would be stored.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Database Class (DB.php)
DB class handles all the operations related to the database using PHP PDO extension and MySQL. For example, connect to the database, fetch, insert, update and delete the record from the database. You only need to change the $dbHost, $dbUsername, $dbPassword, and $dbName variables value as per the database credentials.

<?php
/*
 * DB Class
 * This class is used for database related (connect, get, insert, update, and delete) operations
 * with PHP Data Objects (PDO)
 * @author CodexWorld.com
 * @url http://www.codexworld.com
 * @license http://www.codexworld.com/license
 */
class DB {
    // Database credentials
    private $dbHost = 'localhost';
    private $dbUsername = 'root';
    private $dbPassword = '';
    private $dbName = 'codexworld';
    public $db;
    
    /*
     * Connect to the database and return db connecction
     */
    public function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            try{
                $conn = new PDO("mysql:host=".$this->dbHost.";dbname=".$this->dbName, $this->dbUsername, $this->dbPassword);
                $conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $this->db = $conn;
            }catch(PDOException $e){
                die("Failed to connect with MySQL: " . $e->getMessage());
            }
        }
    }
    
    /*
     * Returns rows from the database based on the conditions
     * @param string name of the table
     * @param array select, where, order_by, limit and return_type conditions
     */
    public function getRows($table,$conditions = array()){
        $sql = 'SELECT ';
        $sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
        $sql .= ' FROM '.$table;
        if(array_key_exists("where",$conditions)){
            $sql .= ' WHERE ';
            $i = 0;
            foreach($conditions['where'] as $key => $value){
                $pre = ($i > 0)?' AND ':'';
                $sql .= $pre.$key." = '".$value."'";
                $i++;
            }
        }
        
        if(array_key_exists("order_by",$conditions)){
            $sql .= ' ORDER BY '.$conditions['order_by']; 
        }
        
        if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            $sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit']; 
        }elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            $sql .= ' LIMIT '.$conditions['limit']; 
        }
        
        $query = $this->db->prepare($sql);
        $query->execute();
        
        if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
            switch($conditions['return_type']){
                case 'count':
                    $data = $query->rowCount();
                    break;
                case 'single':
                    $data = $query->fetch(PDO::FETCH_ASSOC);
                    break;
                default:
                    $data = '';
            }
        }else{
            if($query->rowCount() > 0){
                $data = $query->fetchAll(PDO::FETCH_ASSOC);
            }
        }
        return !empty($data)?$data:false;
    }
    
    /*
     * Insert data into the database
     * @param string name of the table
     * @param array the data for inserting into the table
     */
    public function insert($table,$data){
        if(!empty($data) && is_array($data)){
            $columns = '';
            $values = '';
            $i = 0;
            if(!array_key_exists('created',$data)){
                $data['created'] = date("Y-m-d H:i:s");
            }
            if(!array_key_exists('modified',$data)){
                $data['modified'] = date("Y-m-d H:i:s");
            }

            $columnString = implode(',', array_keys($data));
            $valueString = ":".implode(',:', array_keys($data));
            $sql = "INSERT INTO ".$table." (".$columnString.") VALUES (".$valueString.")";
            $query = $this->db->prepare($sql);
            foreach($data as $key=>$val){
                $val = htmlspecialchars(strip_tags($val));
                $query->bindValue(':'.$key, $val);
            }
            $insert = $query->execute();
            if($insert){
                $data['id'] = $this->db->lastInsertId();
                return $data;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
    /*
     * Update data into the database
     * @param string name of the table
     * @param array the data for updating into the table
     * @param array where condition on updating data
     */
    public function update($table,$data,$conditions){
        if(!empty($data) && is_array($data)){
            $colvalSet = '';
            $whereSql = '';
            $i = 0;
            if(!array_key_exists('modified',$data)){
                $data['modified'] = date("Y-m-d H:i:s");
            }
            foreach($data as $key=>$val){
                $pre = ($i > 0)?', ':'';
                $val = htmlspecialchars(strip_tags($val));
                $colvalSet .= $pre.$key."='".$val."'";
      &nnbsp; $i++;
            }
            if(!empty($conditions)&& is_array($conditions)){
                $whereSql .= ' WHERE ';
                $i = 0;
                foreach($conditions as $key => $value){
                    $pre = ($i > 0)?' AND ':'';
                    $whereSql .= $pre.$key." = '".$value."'";
                    $i++;
                }
            }
            $sql = "UPDATE ".$table." SET ".$colvalSet.$whereSql;
            $query = $this->db->prepare($sql);
            $update = $query->execute();
            return $update?$query->rowCount():false;
        }else{
            return false;
        }
    }
    
    /*
     * Delete data from the database
     * @param string name of the table
     * @param array where condition on deleting data
     */
    public function delete($table,$conditions){
        $whereSql = '';
        if(!empty($conditions)&& is_array($conditions)){
            $whereSql .= ' WHERE ';
            $i = 0;
            foreach($conditions as $key => $value){
                $pre = ($i > 0)?' AND ':'';
                $whereSql .= $pre.$key." = '".$value."'";
                $i++;
            }
        }
        $sql = "DELETE FROM ".$table.$whereSql;
        $delete = $this->db->exec($sql);
        return $delete?$delete:false;
    }
}
action.php (fetch, insert, update, and delete records)
This file handles the requests coming from the HTML page by AngularJS and DB class helps to database related operation. Based on the request, user data would read, add, update, delete from the database. Here the code is executed based on the type. type would be four types, view, add, edit, and delete. The following operations can happen based on the type.
view: fetch the records from the database, records and status message returns as JSON format.
add: insert the record in the database, inserted data and status message returns as JSON format.
edit: update the record in the database, status message returns as JSON format.
delete: delete the record from the database, status message returns as JSON format.

<?php
include 'DB.php';
$db = new DB();
$tblName = 'users';
if(isset($_REQUEST['type']) && !empty($_REQUEST['type'])){
    $type = $_REQUEST['type'];
    switch($type){
        case "view":
            $records = $db->getRows($tblName);
            if($records){
                $data['records'] = $db->getRows($tblName);
                $data['status'] = 'OK';
            }else{
                $data['records'] = array();
                $data['status'] = 'ERR';
            }
            echo json_encode($data);
            break;
        case "add":
            if(!empty($_POST['data'])){
                $userData = array(
                    'name' => $_POST['data']['name'],
                    'email' => $_POST['data']['email'],
                    'phone' => $_POST['data']['phone']
                );
                $insert = $db->insert($tblName,$userData);
                if($insert){
                    $data['data'] = $insert;
                    $data['status'] = 'OK';
                    $data['msg'] = 'User data has been added successfully.';
                }else{
                    $data['status'] = 'ERR';
                    $data['msg'] = 'Some problem occurred, please try again.';
                }
            }else{
                $data['status'] = 'ERR';
                $data['msg'] = 'Some problem occurred, please try again.';
            }
            echo json_encode($data);
            break;
        case "edit":
            if(!empty($_POST['data'])){
                $userData = array(
                    'name' => $_POST['data']['name'],
                    'email' => $_POST['data']['email'],
                    'phone' => $_POST['data']['phone']
                );
                $condition = array('id' => $_POST['data']['id']);
                $update = $db->update($tblName,$userData,$condition);
                if($update){
                    $data['status'] = 'OK';
                    $data['msg'] = 'User data has been updated successfully.';
                }else{
                    $data['status'] = 'ERR';
                    $data['msg'] = 'Some problem occurred, please try again.';
                }
            }else{
                $data['status'] = 'ERR';
                $data['msg'] = 'Some problem occurred, please try again.';
            }
            echo json_encode($data);
            break;
        case "delete":
            if(!empty($_POST['id'])){
                $condition = array('id' => $_POST['id']);
                $delete = $db->delete($tblName,$condition);
                if($delete){
                    $data['status'] = 'OK';
                    $data['msg'] = 'User data has been deleted successfully.';
                }else{
                    $data['status'] = 'ERR';
                    $data['msg'] = 'Some problem occurred, please try again.';
                }
            }else{
                $data['status'] = 'ERR';
                $data['msg'] = 'Some problem occurred, please try again.';
            }
            echo json_encode($data);
            break;
        default:
            echo '{"status":"INVALID"}';
    }
}
index.html (View File)
This is the main view file, where all the users are listed with add, edit, and delete links. Also, the add, update, delete operations are done in this file.

Bootstrap & jQuery Libraries:
Bootstrap CSS & JS library need to be included if you want to use Bootstrap table and form structure, otherwise, omit it.


 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
AngularJS Library: Include the AngularJS library.

<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
AngularJS JavaScript Code:
At first, the application is defined using AngularJS module, then application controller is defined to control the application. The following AngularJS functions are defined to handles the CRUD operations.
$scope.getRecords: The request is sent to the action.php file and store the response data into $scope.users.
$scope.saveUser: The user data is sent to the action.php file and insert or update the data in the database. At the time of update, the updated data is stored in the respective index of $scope.users. At the time of insert, the inserted data to be pushed to $scope.users. Once the operation is done, form data is reset and the status message is shown.
$scope.addUser: $scope.saveUser is called with "add" request.
$scope.editUser: User data is stored in $scope.tempUserData, $scope.index is defined and the form is appear.
$scope.updateUser: $scope.saveUser is called with "edit" request.
$scope.deleteUser: The request is sent to the action.php file for delete data from the database. Based on the response, user data is removed from the user list and status message is shown.
$scope.messageSuccess: Displays the success message.
$scope.messageError: Displays the error message.

// define application
angular.module("crudApp", [])
.controller("userController", function($scope,$http){
    $scope.users = [];
    $scope.tempUserData = {};
    // function to get records from the database
    $scope.getRecords = function(){
        $http.get('action.php', {
            params:{
                'type':'view'
            }
        }).success(function(response){
            if(response.status == 'OK'){
                $scope.users = response.records;
            }
        });
    };
    
    // function to insert or update user data to the database
    $scope.saveUser = function(type){
        var data = $.param({
            'data':$scope.tempUserData,
            'type':type
        });
        var config = {
            headers : {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
            }
        };
        $http.post("action.php", data, config).success(function(response){
            if(response.status == 'OK'){
                if(type == 'edit'){
                    $scope.users[$scope.index].id = $scope.tempUserData.id;
                    $scope.users[$scope.index].name = $scope.tempUserData.name;
                    $scope.users[$scope.index].email = $scope.tempUserData.email;
                    $scope.users[$scope.index].phone = $scope.tempUserData.phone;
                    $scope.users[$scope.index].created = $scope.tempUserData.created;
                }else{
                    $scope.users.push({
                        id:response.data.id,
                        name:response.data.name,
                        email:response.data.email,
                        phone:response.data.phone,
                        created:response.data.created
                    });
                    
                }
                $scope.userForm.$setPristine();
                $scope.tempUserData = {};
                $('.formData').slideUp();
                $scope.messageSuccess(response.msg);
            }else{
                $scope.messageError(response.msg);
            }
        });
    };
    
    // function to add user data
    $scope.addUser = function(){
        $scope.saveUser('add');
    };
    
    // function to edit user data
    $scope.editUser = function(user){
        $scope.tempUserData = {
            id:user.id,
            name:user.name,
            email:user.email,
            phone:user.phone,
            created:user.created
        };
        $scope.index = $scope.users.indexOf(user);
        $('.formData').slideDown();
    };
    
    // function to update user data
    $scope.updateUser = function(){
        $scope.saveUser('edit');
    };
    
    // function to delete user data from the database
    $scope.deleteUser = function(user){
        var conf = confirm('Are you sure to delete the user?');
        if(conf === true){
            var data = $.param({
                'id': user.id,
                'type':'delete'    
            });
            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }    
            };
            $http.post("action.php",data,config).success(function(response){
                if(response.status == 'OK'){
                    var index = $scope.users.indexOf(user);
                    $scope.users.splice(index,1);
                    $scope.messageSuccess(response.msg);
                }else{
                    $scope.messageError(response.msg);
                }
            });
        }
    };
    
    // function to display success message
    $scope.messageSuccess = function(msg){
        $('.alert-success > p').html(msg);
        $('.alert-success').show();
        $('.alert-success').delay(5000).slideUp(function(){
            $('.alert-success > p').html('');
        });
    };
    
    // function to display error message
    $scope.messageError = function(msg){
        $('.alert-danger > p').html(msg);
        $('.alert-danger').show();
        $('.alert-danger').delay(5000).slideUp(function(){
            $('.alert-danger > p').html('');
        });
    };
});

 
HTML Code:
On page load, getRecords() function (defined by ng-init) is initialized which will fetch the records from the database. AngularJS ng-repeat directive helps to list the users data and AngularJS expression ({{ expression }}) is used to binds the user data to HTML.

The following directives will be used in the HTML code.
ng-app directive defines an AngularJS application to HTML.
ng-controller directive defines the application controller.
ng-init directive initializes the given expression.
ng-model directive binds the HTML input controls to application data.
ng-hide directive hides the HTML element based on the provided expression.
ng-click directive tells AngularJS what to do when an HTML element is clicked.
ng-repeat directive repeats a set of HTML, based on given number of times.

Expressions are used to bind the application data to HTML in AngularJS. AngularJS expressions are written inside the double curly braces or inside a ng-bind directive.

<body ng-app="crudApp">
<div class="container" ng-controller="userController" ng-init="getRecords()">
    <div class="row">
        <div class="panel panel-default users-content">
            <div class="panel-heading">Users <a href="javascript:void(0);" class="glyphicon glyphicon-plus" onclick="$('.formData').slideToggle();"></a></div>
            <div class="alert alert-danger none"><p></p></div>
            <div class="alert alert-success none"><p></p></div>
            <div class="panel-body none formData">
                <form class="form" name="userForm">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" class="form-control" name="name" ng-model="tempUserData.name"/>
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="text" class="form-control" name="email" ng-model="tempUserData.email"/>
                    </div>
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="text" class="form-control" name="phone" ng-model="tempUserData.phone"/>
                    </div>
                    <a href="javascript:void(0);" class="btn btn-warning" onclick="$('.formData').slideUp();">Cancel</a>
                    <a href="javascript:void(0);" class="btn btn-success" ng-hide="tempUserData.id" ng-click="addUser()">Add User</a>
                    <a href="javascript:void(0);" class="btn btn-success" ng-hide="!tempUserData.id" ng-click="updateUser()">Update User</a>
                </form>
            </div>
            <table class="table table-striped">
                <tr>
                    <th width="5%">#</th>
                    <th width="20%">Name</th>
                    <th width="30%">Email</th>
                    <th width="20%">Phone</th>
                    <th width="14%">Created</th>
                    <th width="10%"></th>
                </tr>
                <tr ng-repeat="user in users | orderBy:'-created'">
                    <td>{{$index + 1}}</td>
                    <td>{{user.name}}</td>
                    <td>{{user.email}}</td>
                    <td>{{user.phone}}</td>
                    <td>{{user.created}}</td>
                    <td>
                        <a href="javascript:void(0);" class="glyphicon glyphicon-edit" ng-click="editUser(user)"></a>
                        <a href="javascript:void(0);" class="glyphicon glyphicon-trash" ng-click="deleteUser(user)"></a>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</div>
</body>
CSS Code:
The following CSS is used for design purpose in our example application.

/* required style*/ 
.none{display: none;}

/* optional styles */
table tr th, table tr td{font-size: 1.2rem;}
.row{ margin:20px 20px 20px 20px;width: 100%;}
.glyphicon{font-size: 20px;}
.glyphicon-plus{float: right;}
a.glyphicon{text-decoration: none;cursor: pointer;}
.glyphicon-trash{margin-left: 10px;}
.alert{
    width: 50%;
    border-radius: 0;
    margin-top: 10px;
    margin-left: 10px;
}
Conclusion:
In this article, we are trying to help beginners to implement view, add, edit, and delete records with AngularJS. If you want to update this example script, you can share your idea by commenting here
Share:

Angular JS CRUD

AngularJS CRUD: Example Using MySQLi Database
AngularJS is commonly used for creating a single page application. So, it becomes challenging for users to interact their application with the database and perform CRUD operation in it.

In this tutorial, we are going to create an AngularJS CRUD Example and will also explain each CRUD operation in detail.

For storing of data, we are going to use MySQLi database.

We will learn:
Read data from the database.
Insert data into the database.
Update existing data in the database.
Delete data from the database.
In order to understand easily and effectively, we are going to create an application which will perform all the above-mentioned operation.

We will also explain each process while the process of creating the application.

Speciality of the Application:
Users can Add new entries of employees in the database.
Users can Read, Update and Delete the existing employee details.
Application will also contains a search bar to search the list of employee according to the query given.
Watch AngularJS CRUD Application Demo or download code from the link given below.

DOWNLOAD SCRIPT   
Application Development Process:
Step 1: Create file structure of the application.

Follow the image given below and create your application structure in the same way as given in the image.

Otherwise, you may face some problem regarding the working of the application.

AngularJS CRUD Directory Structure

Step 2: Setting up the database.

Create a database name “employee“.

Now, inside employee database, create a table name “emp_details” with different fields using the query given below:

CREATE TABLE emp_details (
emp_id int(255) NOT NULL AUTO_INCREMENT,
emp_name varchar(255) NOT NULL,
emp_email varchar(255) NOT NULL,
emp_gender varchar(255) NOT NULL,
emp_address varchar(255) NOT NULL,
PRIMARY KEY (emp_id)
);
Copy
OR
Download the database .sql file from this link and import it directly into your database. It will automatically create a table “emp_details” with different columns/fields to store employee details in it.

Step 3: Connecting to MySQLi database.

In database_connections.php, write MySQLi query to connect to the database.

<?php
// Connecting to database as mysqli_connect("hostname", "username", "password", "database name");
$con = mysqli_connect("localhost", "root", "", "employee");
?>
Copy
Note: We will include this connection file in each CRUD opearation performing file.

Step 4: Create index.html file for the application.

index.html
This file contains the layout of the application. It includes two seperate form template to insert and update employee details.

Some AngularJS built-in directives have also used in it such as ng-repeat, ng-show, ng-hide, ng-click etc. These directives add some special behaviour into the application to make it more interactive.

Note: – To know about the functionality of different built-in directives, read our blog AngularJS Directives.

Also, for search bar and other filtering functionality, read blog AngularJS Filters.

<html ng-app="crudApp">
<head>
<title>AngularJS Directive Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Include Bootstrap CSS -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<!-- Include main CSS -->
<link rel="stylesheet" type="text/css" href="css/style.css">
<!-- Include jQuery library -->
<script src="js/jQuery/jquery.min.js"></script>
<!-- Include AngularJS library -->
<script src="lib/angular/angular.min.js"></script>
<!-- Include Bootstrap Javascript -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container wrapper" ng-controller="DbController">
<h1 class="text-center">AngularJS CRUD Operations Demo</h1>
<nav class="navbar navbar-default">
<div class="navbar-header">
<div class="alert alert-default navbar-brand search-box">
<button class="btn btn-primary" ng-show="show_form" ng-click="formToggle()">Add Employee <span class="glyphicon glyphicon-plus" aria-hidden="true"></span></button>
</div>
<div class="alert alert-default input-group search-box">
<span class="input-group-btn">
<input type="text" class="form-control" placeholder="Search Employee Details Into Database..." ng-model="search_query">
</span>
</div>
</div>
</nav>
<div class="col-md-6 col-md-offset-3">

<!-- Include form template which is used to insert data into database -->
<div ng-include src="'templates/form.html'"></div>

<!-- Include form template which is used to edit and update data into database -->
<div ng-include src="'templates/editForm.html'"></div>
</div>
<div class="clearfix"></div>

<!-- Table to show employee detalis -->
<div class="table-responsive">
<table class="table table-hover">
<tr>
<th>Emp ID</th>
<th>Employee Name</th>
<th>Email Address</th>
<th>Gender</th>
<th>Address</th>
<th></th>
<th></th>
</tr>
<tr ng-repeat="detail in details| filter:search_query">
<td>
<span>{{detail.emp_id}}</span></td>
<td>{{detail.emp_name}}</td>
<td>{{detail.emp_email}}</td>
<td>{{detail.emp_gender}}</td>
<td>{{detail.emp_address}}</td>
<td>
<button class="btn btn-warning" ng-click="editInfo(detail)" title="Edit"><span class="glyphicon glyphicon-edit"></span></button>
</td>
<td>
<button class="btn btn-danger" ng-click="deleteInfo(detail)" title="Delete"><span class="glyphicon glyphicon-trash"></span></button>
</td>
</tr>
</table>
</div>
</div>
</div>
<!-- Include controller -->
<script src="js/angular-script.js"></script>
</body>
</html>
Copy
Now, we have all the basic settings for the application.

So, let’s focus on the CRUD operation and start from reading the database.

1. Read From Database : Get Employee Detail
The downloaded database .sql files that you have imported in the employee database contains some dummy data. So, now we are going to retrieve and read these data from the database and display it in the application’s main page.

For this, create a module name crudApp and a controller name DbController in the angular-script.js. 

Also, inside controller create a function getInfo() which send request to empDetails.php.

angular-script.js
// Application module
var crudApp = angular.module('crudApp',[]);
crudApp.controller("DbController",['$scope','$http', function($scope,$http){

// Function to get employee details from the database
getInfo();
function getInfo(){
// Sending request to EmpDetails.php files
$http.post('databaseFiles/empDetails.php').success(function(data){
// Stored the returned data into scope
$scope.details = data;
});
}
Copy
Here, getInfo() function sends request to empDetails.php page via $http.post method.

Note:- $http is one of the most important service of AngularJS which is used to transfer data. For more info, read our blog AngularJS – http.

Now, empDetails.php contains select query and retrives all the employee details stored in the employee database. These details are returned in the JSON format.

empDetails.php
<?php
// Including database connections
require_once 'database_connections.php';
// mysqli query to fetch all data from database
$query = "SELECT * from emp_details ORDER BY emp_id ASC";
$result = mysqli_query($con, $query);
$arr = array();
if(mysqli_num_rows($result) != 0) {
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
}
// Return json array containing data from the databasecon
echo $json_info = json_encode($arr);
?>
Copy
The returned json data has stored in $scope.details. 

Now, the details property has all the employees details which can be displayed in the application index.html page using ng-repeat directive.

<html ng-app="crudApp">
...
<body>
<div class="container wrapper" ng-controller="DbController">
...
<!-- Table to show employee detalis -->
<div class="table-responsive">
<table class="table table-hover">
<tr>
<th>Emp ID</th>
<th>Employee Name</th>
<th>Email Address</th>
<th>Gender</th>
<th>Address</th>
<th></th>
<th></th>
</tr>
<tr ng-repeat="detail in details| filter:search_query">
<td>
<span>{{detail.emp_id}}</span></td>
<td>{{detail.emp_name}}</td>
<td>{{detail.emp_email}}</td>
<td>{{detail.emp_gender}}</td>
<td>{{detail.emp_address}}</td>
<td>
<button class="btn btn-warning" ng-click="editInfo(detail)" title="Edit"><span class="glyphicon glyphicon-edit"></span></button>
</td>
<td>
<button class="btn btn-danger" ng-click="deleteInfo(detail)" title="Delete"><span class="glyphicon glyphicon-trash"></span></button>
</td>
</tr>
</table>
</div>
...
</body>
</html>
Copy
Process outputAngular CRUD Read Operation
Here, the employee details table contains two buttons – one for edit and another for delete. We will read about the functionality of these buttons further in this tutorial.

That’s ends with the reading part. Next part is about inserting employee information into the database.

2. Insert Into Database : Employee Detail
To insert employee details, we need a form with different input fields.

So, let’s create a form.html page which contain a form to insert employee details.

form.html
<!-- Form used to add new entries of employee in database -->
<form class="form-horizontal alert alert-warning" name="empList" id="empForm" ng-submit="insertInfo(empInfo);" hidden>
<h3 class="text-center">Insert Employee Details Into Database</h3>
<div class="form-group">
<label for="Name">Employee Name:</label>
<input type="text" name="emp_name" class="form-control" placeholder="Enter Employee Name" ng-model="empInfo.name" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.emp_name.$invalid && empList.emp_name.$dirty">Name field is Empty!</p>
</div>
<div class="form-group">
<label for="Email">Email Address:</label>
<input type="email" name="emp_email" class="form-control" placeholder="Enter Employee Email Address" ng-model="empInfo.email" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.emp_email.$invalid && empList.emp_email.$dirty">Invalid Email!</p>
</div>
<div class="form-group">
<label for="Gender">Gender:</label>
<label for="" class="radio-inline gender">
<input type="radio" name="emp_gender" value="male" ng-model="empInfo.gender">Male
</label>
<label for="" class="radio-inline gender">
<input type="radio" name="emp_gender" value="female" ng-model="empInfo.gender">Female
</label>
</div>
<div class="form-group">
<label for="Address">Address:</label>
<input type="text" name="emp_address" class="form-control" placeholder="Enter Employee Address" ng-model="empInfo.address" autofocus required />
</div>
<div class="form-group">
<p class="text-danger" ng-show="empList.emp_address.$invalid && empList.emp_address.$dirty">Address field is Empty!</p>
</div>
<div class="form-group">
<button class="btn btn-warning" ng-disabled="empList.$invalid">Add Into Database</button>
</div>
</form>
Copy
Every input field has ng-model directive associated with them which will bind and store users input values in the empInfo. When the user will click on the submit button ( Here, Add Into Database button), empInfo will be passed, as an argument, to the insertInfo() function.

angular-script.js
$scope.insertInfo = function(info){
$http.post('databaseFiles/insertDetails.php',{"name":info.name,"email":info.email,"address":info.address,"gender":info.gender}).success(function(data){
if (data == true) {
getInfo();
// Hide details insertion form
$('#empForm').css('display', 'none');
}
});
}
Copy
insertInfo() function communicates with insertDetails.php file and send the submitted data to it.

insertDetails.php
<?php
// Including database connections
require_once 'database_connections.php';
// Fetching and decoding the inserted data
$data = json_decode(file_get_contents("php://input"));
// Escaping special characters from submitting data & storing in new variables.
$name = mysqli_real_escape_string($con, $data->name);
$email = mysqli_real_escape_string($con, $data->email);
$gender = mysqli_real_escape_string($con, $data->gender);
$address = mysqli_real_escape_string($con, $data->address);

// mysqli insert query
$query = "INSERT into emp_details (emp_name,emp_email,emp_gender,emp_address) VALUES ('$name','$email','$gender','$address')";
// Inserting data into database
mysqli_query($con, $query);
echo true;
?>
Copy
In insertDetails.php, the sent values are first decoded into JSON format. Then, they are filtered and stored into different variable.

These variables are then used to store data into the database. When the data has submitted successfully, it returns true in response to insertInfo() function.

At the same time getInfo() function get called by the insertInfo() function which displays the newly inserted details in the employee detail table.

Process outputAngular CRUD Insert Operation
Now, let’s understand the update process.

3. Update Database: Existing Employee Details
If you remember, we have added an edit button in the index.html page while displaying the employee details in the table. Now, it time to understand its functionality.

This edit button contains ng-click directive which on click calls editInfo(detail) function and pass the details of the clicked row’s data as an argument.

The passed argument then stored into a new scope property, $scope.currentUser, and this propert is used by the editForm.php to display the current employee details in the edit form.

angular-script.js
$scope.currentUser = {};
$scope.editInfo = function(info){
$scope.currentUser = info;
$('#empForm').slideUp();
$('#editForm').slideToggle();
}
Copy
Now, we are going to create an edit form which will use the above mentioned scope’s property for the updation process.

editForm.html
<!-- Form used for updation of data into database -->
<form class="form-horizontal alert alert-warning" id="editForm" ng-submit="UpdateInfo(currentUser)" hidden>
<h3 class="text-center">Update Employee Details</h3>
<div class="form-group">
<label for="Name">Employee Name:</label>
<input type="text" class="form-control" ng-model="currentUser.emp_name" value="{{currentUser.name}}">
</div>
<div class="form-group">
<label for="Email">Email Address:</label>
<input type="email" class="form-control" ng-model="currentUser.emp_email" value="{{currentUser.emp_email}}">
</div>
<div class="form-group">
<label for="Gender">Gender:</label>
<label for="" class="radio-inline gender">
<input type="radio" ng-model="currentUser.emp_gender" value="male" >Male
</label>
<label for="" class="radio-inline gender">
<input type="radio" name="gender" ng-model="currentUser.emp_gender" value="female">Female
</label>
</div>
<div class="form-group">
<label for="Address">Address:</label>
<input type="text" class="form-control" ng-model="currentUser.emp_address" value="{{currentUser.emp_address}}">
</div>
<div class="form-group">
<button class="btn btn-warning" ng-disabled="empList.$invalid" ng-click="updateMsg(currentUser.emp_id)">Update</button>
</div>
</form>
Copy
Now, when a user will change the current values of input field and click on submit button, here update button, another function UpdateInfo() get called containing currentUser as an argument( which contains the updated values of the input fields ).

angular-script.js
$scope.UpdateInfo = function(info){
$http.post('databaseFiles/updateDetails.php',{"id":info.emp_id,"name":info.emp_name,"email":info.emp_email,"address":info.emp_address,"gender":info.emp_gender}).success(function(data){
$scope.show_form = true;
if (data == true) {
getInfo();
}
});
}
Copy
Now, updateInfo() function communicates with the updateDetails.php and send all the updated data, also contain the id of employee, through $http.post method.

updateDetails.php
<?php
// Including database connections
require_once 'database_connections.php';
// Fetching the updated data & storin in new variables
$data = json_decode(file_get_contents("php://input"));
// Escaping special characters from updated data
$id = mysqli_real_escape_string($con, $data->id);
$name = mysqli_real_escape_string($con, $data->name);
$email = mysqli_real_escape_string($con, $data->email);
$gender = mysqli_real_escape_string($con, $data->gender);
$address = mysqli_real_escape_string($con, $data->address);
// mysqli query to insert the updated data
$query = "UPDATE emp_details SET emp_name='$name',emp_email='$email',emp_gender='$gender',emp_address='$address' WHERE emp_id=$id";
mysqli_query($con, $query);
echo true;
?>
Copy
In updateDetails.php, the sent data get decoded and that particular row get updated with the new values. After succuessfully updation, it return true status as a reply.

When the UpdateInfo() method receives the true value, it calls getInfo() to show details of the updated table.

Process outputAngular CRUD Update Operation
Update process ends here. Now, it’s time to have a look at the delete process.

4. Delete From Database: Existing Employee Details
Now, it time to understand the functionality of the delete button that we have added in the index.html page while displaying the employee details in the table.

Delete button contains ng-click directive as an attribute which on click calls deleteInfo(detail) function and pass the details of the clicked row’s data as an argument to it.

angular-script.js
$scope.deleteInfo = function(info){
$http.post('databaseFiles/deleteDetails.php',{"del_id":info.emp_id}).success(function(data){
if (data == true) {
getInfo();
}
});
}
Copy
Now, deleteInfo() function communicates with the deleteDetails.php and send employee ID of the clicked row through $http.post method.

deleteDetails.php
<?php
require_once 'database_connections.php';
$data = json_decode(file_get_contents("php://input"));
$query = "DELETE FROM emp_details WHERE emp_id=$data->del_id";
mysqli_query($con, $query);
echo true;
?>
Copy
In deleteDetails.php, the sent data get decoded and the row containing that particular ID get deleted. After succuessfully deletion, it return true status as a reply.

When the deleteInfo() method receives the true value, it calls getInfo() to show details of the updated table.

Process outputAngular CRUD Delete Operation
That ends the complete CRUD operation.

Application’s Styling Part
For responsiveness and icons, we have used bootstrap in the application.

Also, used some external CSS to improve designing part.

style.css
Contain CSS of the application.

@import url(http://fonts.googleapis.com/css?family=Raleway);
.wrapper{
min-height: 960px;
}
form#empForm, form#editForm {
padding: 0 35px 15px;
}
label.gender {
padding-top: 0 !important;
}
table tr th{
background: #f8f8f8;
}
.search-box {
padding-bottom: 0;
}
@media screen and (max-width: 368px){
.wrapper{
min-width: 340px;
}
}
Copy
Conclusion:
Hope you guys enjoyed this blog and learned the concepts of CRUD in AngularJS. Please write your comments from the space given below and keep in touch with us for more interesting blogs 🙂

Read Process
Insert Process
Update Process
Delete Process
Share:

Live Chat With Us

My Blog List

Search This Blog

Locations

Training

Pages

My Blog List

Blog Archive

Privacy policy