AngularJS CRUD Insert Update Delete with PHP and MySQL

Welcome on infinityknow.com – Examples ,The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to AngularJS CRUD Insert Update Delete with PHP and MySQL

In this post we will show you Best way to implement AngularJS CRUD Example | Create, Read, Update,Delete Using PHP, hear for How to AngularJS – Insert Update Delete using PHP and MySQL with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

record_database Table Creation

CREATE TABLE `products` (
 `product_id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `contact` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `isactive` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
 PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

record_database Class (DB.php)

<?php
/*
 * DB Class
 * This class is used for record_database related (connect, get, insert, update, and delete) operations
 * with PHP record_data Objects (PDO)
 * @author    infinityknow.com
 * @url       https://www.infinityknow.com
 * @license   https://www.infinityknow.com/license
 */
class DB {
    // record_database credentials
    private $hostName     = 'localhost';
    private $itemName = 'root';
    private $itemPass = 'atmiya25';
    private $myDbName     = 'live24u';
    public $db;
    
    public function __construct(){
        if(!isset($this->db)){
            // Connect to the record_database
            try{
                $conn = new PDO("myquery:host=".$this->hostName.";myDbName=".$this->myDbName, $this->itemName, $this->itemPass);
                $conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $this->db = $conn;
            }catch(PDOException $e){
                die("Failed to connect with Myquery: " . $e->getMessage());
            }
        }
    }
    
    public function selectRows($table,$livecondtion = array()){
        $query = 'SELECT ';
        $query .= array_key_exists("select",$livecondtion)?$livecondtion['select']:'*';
        $query .= ' FROM '.$table;
        if(array_key_exists("where",$livecondtion)){
            $query .= ' WHERE ';
            $i = 0;
            foreach($livecondtion['where'] as $key => $value){
                $pre = ($i > 0)?' AND ':'';
                $query .= $pre.$key." = '".$value."'";
                $i++;
            }
        }
        
        if(array_key_exists("order_by",$livecondtion)){
            $query .= ' ORDER BY '.$livecondtion['order_by']; 
        }
        
        if(array_key_exists("start",$livecondtion) && array_key_exists("limit",$livecondtion)){
            $query .= ' LIMIT '.$livecondtion['start'].','.$livecondtion['limit']; 
        }elseif(!array_key_exists("start",$livecondtion) && array_key_exists("limit",$livecondtion)){
            $query .= ' LIMIT '.$livecondtion['limit']; 
        }
        
        $query = $this->db->prepare($query);
        $query->execute();
        
        if(array_key_exists("return_type",$livecondtion) && $livecondtion['return_type'] != 'all'){
            switch($livecondtion['return_type']){
                case 'count':
                    $record_data = $query->rowCount();
                    break;
                case 'single':
                    $record_data = $query->fetch(PDO::FETCH_ASSOC);
                    break;
                default:
                    $record_data = '';
            }
        }else{
            if($query->rowCount() > 0){
                $record_data = $query->fetchAll(PDO::FETCH_ASSOC);
            }
        }
        return !empty($record_data)?$record_data:false;
    }
    
    /*
     * Insert record_data into the record_database
     * @param string name of the table
     * @param array the record_data for inserting into the table
     */
    public function insert($table,$record_data){
        if(!empty($record_data) && is_array($record_data)){
            $columns = '';
            $values  = '';
            $i = 0;
            if(!array_key_exists('created',$record_data)){
                $record_data['created'] = date("Y-m-d H:i:s");
            }
            if(!array_key_exists('modified',$record_data)){
                $record_data['modified'] = date("Y-m-d H:i:s");
            }

            $columnString = implode(',', array_keys($record_data));
            $valueString = ":".implode(',:', array_keys($record_data));
            $query = "INSERT INTO ".$table." (".$columnString.") VALUES (".$valueString.")";
            $query = $this->db->prepare($query);
            foreach($record_data as $key=>$val){
                $val = htmlspecialchars(strip_tags($val));
                $query->bindValue(':'.$key, $val);
            }
            $insert = $query->execute();
            if($insert){
                $record_data['product_id'] = $this->db->lastInsertproduct_id();
                return $record_data;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
    /*
     * Update record_data into the record_database
     * @param string name of the table
     * @param array the record_data for updating into the table
     * @param array where condition on updating record_data
     */
    public function update($table,$record_data,$livecondtion){
        if(!empty($record_data) && is_array($record_data)){
            $oldcolmval = '';
            $newwherecondition = '';
            $i = 0;
            if(!array_key_exists('modified',$record_data)){
                $record_data['modified'] = date("Y-m-d H:i:s");
            }
            foreach($record_data as $key=>$val){
                $pre = ($i > 0)?', ':'';
                $val = htmlspecialchars(strip_tags($val));
                $oldcolmval .= $pre.$key."='".$val."'";
      &nnbsp;         $i++;
            }
            if(!empty($livecondtion)&& is_array($livecondtion)){
                $newwherecondition .= ' WHERE ';
                $i = 0;
                foreach($livecondtion as $key => $value){
                    $pre = ($i > 0)?' AND ':'';
                    $newwherecondition .= $pre.$key." = '".$value."'";
                    $i++;
                }
            }
            $query = "UPDATE ".$table." SET ".$oldcolmval.$newwherecondition;
            $query = $this->db->prepare($query);
            $update = $query->execute();
            return $update?$query->rowCount():false;
        }else{
            return false;
        }
    }
    
    public function delete($table,$livecondtion){
        $newwherecondition = '';
        if(!empty($livecondtion)&& is_array($livecondtion)){
            $newwherecondition .= ' WHERE ';
            $i = 0;
            foreach($livecondtion as $key => $value){
                $pre = ($i > 0)?' AND ':'';
                $newwherecondition .= $pre.$key." = '".$value."'";
                $i++;
            }
        }
        $query = "DELETE FROM ".$table.$newwherecondition;
        $delete = $this->db->exec($query);
        return $delete?$delete:false;
    }
}

mainpage.php (fetch, insert, update, and delete records)

<?php
include 'DB.php';
$db = new DB();
$yourtable_name = 'products';
if(isset($_REQUEST['type']) && !empty($_REQUEST['type'])){
    $type = $_REQUEST['type'];
    switch($type){
        case "view":
            $records = $db->selectRows($yourtable_name);
            if($records){
                $record_data['records'] = $db->selectRows($yourtable_name);
                $record_data['isactive'] = 'OK';
            }else{
                $record_data['records'] = array();
                $record_data['isactive'] = 'ERR';
            }
            echo json_encode($record_data);
            break;
        case "add":
            if(!empty($_POST['record_data'])){
                $itemrecord_data = array(
                    'name' => $_POST['record_data']['name'],
                    'email' => $_POST['record_data']['email'],
                    'contact' => $_POST['record_data']['contact']
                );
                $insert = $db->insert($yourtable_name,$itemrecord_data);
                if($insert){
                    $record_data['record_data'] = $insert;
                    $record_data['isactive'] = 'OK';
                    $record_data['message'] = 'item record_data has been added successfully.';
                }else{
                    $record_data['isactive'] = 'ERR';
                    $record_data['message'] = 'Some error generate or stuck occurred, please try again.';
                }
            }else{
                $record_data['isactive'] = 'ERR';
                $record_data['message'] = 'Some error generate or stuck occurred, please try again.';
            }
            echo json_encode($record_data);
            break;
        case "edit":
            if(!empty($_POST['record_data'])){
                $itemrecord_data = array(
                    'name' => $_POST['record_data']['name'],
                    'email' => $_POST['record_data']['email'],
                    'contact' => $_POST['record_data']['contact']
                );
                $condition = array('product_id' => $_POST['record_data']['product_id']);
                $update = $db->update($yourtable_name,$itemrecord_data,$condition);
                if($update){
                    $record_data['isactive'] = 'OK';
                    $record_data['message'] = 'item record_data has been updated successfully.';
                }else{
                    $record_data['isactive'] = 'ERR';
                    $record_data['message'] = 'Some error generate or stuck occurred, please try again.';
                }
            }else{
                $record_data['isactive'] = 'ERR';
                $record_data['message'] = 'Some error generate or stuck occurred, please try again.';
            }
            echo json_encode($record_data);
            break;
        case "delete":
            if(!empty($_POST['product_id'])){
                $condition = array('product_id' => $_POST['product_id']);
                $delete = $db->delete($yourtable_name,$condition);
                if($delete){
                    $record_data['isactive'] = 'OK';
                    $record_data['message'] = 'item record_data has been deleted successfully.';
                }else{
                    $record_data['isactive'] = 'ERR';
                    $record_data['message'] = 'Some error generate or stuck occurred, please try again.';
                }
            }else{
                $record_data['isactive'] = 'ERR';
                $record_data['message'] = 'Some error generate or stuck occurred, please try again.';
            }
            echo json_encode($record_data);
            break;
        default:
            echo '{"isactive":"INVALproduct_id"}';
    }
}

Bootstrap & jQuery Libraries:

<link href="bootstrap.min.css" rel="stylesheet">
<script src="jquery.min.js"></script>
<script src="bootstrap.min.js"></script>
<script src = "angular.min.js"></script>

AngularJS JavaScript Code:

// define application
angular.module("liveApp", [])
.controller("itemController", function($scope,$http){
    $scope.products = [];
    $scope.tempitemrecord_data = {};
    // function to get records from the record_database
    $scope.getRecords = function(){
        $http.get('mainpage.php', {
            params:{
                'type':'view'
            }
        }).success(function(result){
            if(result.isactive == 'OK'){
                $scope.products = result.records;
            }
        });
    };
    
    // function to insert or update item record_data to the record_database
    $scope.saveitem = function(type){
        var record_data = $.param({
            'record_data':$scope.tempitemrecord_data,
            'type':type
        });
        var config = {
            headers : {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
            }
        };
        $http.post("mainpage.php", record_data, config).success(function(result){
            if(result.isactive == 'OK'){
                if(type == 'edit'){
                    $scope.products[$scope.index].product_id = $scope.tempitemrecord_data.product_id;
                    $scope.products[$scope.index].name = $scope.tempitemrecord_data.name;
                    $scope.products[$scope.index].email = $scope.tempitemrecord_data.email;
                    $scope.products[$scope.index].contact = $scope.tempitemrecord_data.contact;
                    $scope.products[$scope.index].created = $scope.tempitemrecord_data.created;
                }else{
                    $scope.products.push({
                        product_id:result.record_data.product_id,
                        name:result.record_data.name,
                        email:result.record_data.email,
                        contact:result.record_data.contact,
                        created:result.record_data.created
                    });
                    
                }
                $scope.itemForm.$setPristine();
                $scope.tempitemrecord_data = {};
                $('.myliveform').slproduct_ideUp();
                $scope.messageSuccess(result.message);
            }else{
                $scope.messageError(result.message);
            }
        });
    };
    
    // function to add item record_data
    $scope.additem = function(){
        $scope.saveitem('add');
    };
    
    // function to edit item record_data
    $scope.edititem = function(item){
        $scope.tempitemrecord_data = {
            product_id:item.product_id,
            name:item.name,
            email:item.email,
            contact:item.contact,
            created:item.created
        };
        $scope.index = $scope.products.indexOf(item);
        $('.myliveform').slproduct_ideDown();
    };
    
    // function to update item record_data
    $scope.updateitem = function(){
        $scope.saveitem('edit');
    };
    
    // function to delete item record_data from the record_database
    $scope.removeItem = function(item){
        var conf = confirm('Are you sure to delete the item?');
        if(conf === true){
            var record_data = $.param({
                'product_id': item.product_id,
                'type':'delete'    
            });
            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }    
            };
            $http.post("mainpage.php",record_data,config).success(function(result){
                if(result.isactive == 'OK'){
                    var ltind = $scope.products.indexOf(item);
                    $scope.products.splice(ltind,1);
                    $scope.messageSuccess(result.message);
                }else{
                    $scope.messageError(result.message);
                }
            });
        }
    };
    
    // function to display success message
    $scope.messageSuccess = function(message){
        $('.alert-success > p').html(message);
        $('.alert-success').show();
        $('.alert-success').delay(5000).slproduct_ideUp(function(){
            $('.alert-success > p').html('');
        });
    };
    
    // function to display error message
    $scope.messageError = function(message){
        $('.alert-danger > p').html(message);
        $('.alert-danger').show();
        $('.alert-danger').delay(5000).slproduct_ideUp(function(){
            $('.alert-danger > p').html('');
        });
    };
});

index.html (View File)

<body ng-app="liveApp">
<div class="container" ng-controller="itemController" ng-init="getRecords()">
    <div class="row">
        <div class="panel panel-default products-content">
            <div class="panel-heading">products <a href="javascript:voproduct_id(0);" class="glyphicon glyphicon-plus" onclick="$('.myliveform').slproduct_ideToggle();"></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 myliveform">
                <form class="form" name="itemForm">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" class="form-control" name="name" ng-model="tempitemrecord_data.name"/>
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="text" class="form-control" name="email" ng-model="tempitemrecord_data.email"/>
                    </div>
                    <div class="form-group">
                        <label>contact</label>
                        <input type="text" class="form-control" name="contact" ng-model="tempitemrecord_data.contact"/>
                    </div>
                    <a href="javascript:voproduct_id(0);" class="btn btn-warning" onclick="$('.myliveform').slproduct_ideUp();">Cancel</a>
                    <a href="javascript:voproduct_id(0);" class="btn btn-success" ng-hproduct_ide="tempitemrecord_data.product_id" ng-click="additem()">Add item</a>
                    <a href="javascript:voproduct_id(0);" class="btn btn-success" ng-hproduct_ide="!tempitemrecord_data.product_id" ng-click="updateitem()">Update item</a>
                </form>
            </div>
            <table class="table table-striped">
                <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>contact</th>
                    <th>Created</th>
                    <th></th>
                </tr>
                <tr ng-repeat="item in products | orderBy:'-created'">
                    <td>{{$index + 1}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.email}}</td>
                    <td>{{item.contact}}</td>
                    <td>{{item.created}}</td>
                    <td>
                        <a href="javascript:voproduct_id(0);" class="glyphicon glyphicon-edit" ng-click="edititem(item)"></a>
                        <a href="javascript:voproduct_id(0);" class="glyphicon glyphicon-trash" ng-click="removeItem(item)"></a>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</div>
</body>

CSS Code:

.none{display: none;}

table tr th, table tr td{font-size: 1.2rem;}
.row{ margin:20px 20px 20px 20px;wproduct_idth: 100%;}
.glyphicon{font-size: 20px;}
.glyphicon-plus{float: right;}
a.glyphicon{text-decoration: none;cursor: pointer;}
.glyphicon-trash{margin-left: 10px;}
.alert{
    wproduct_idth: 50%;
    border-radius: 0;
    margin-top: 10px;
    margin-left: 10px;
}

Example

READ :  Vue-router - Routing using Vuejs - Dynamic Components in Vuejs

I hope you have Got AngularJS CRUD Example with Material Design – Step by Step And how it works.I would Like to have FeadBack From My Blog(infinityknow.com) readers.Your Valuable FeadBack,Any Question,or any Comments abaout This Article(infinityknow.com) Are Most Always Welcome.