Site icon FahmidasClassroom

AngularJS CRUD Operations using PHP and MySQL

Ajs Crud

The  tutorial will help you to learn angularjs crud operation using php  and mysql database.

Steps:

1. Create a database named angularjs and table named users


CREATE TABLE `users` (
`id` int (11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`phone` varchar(15) NOT NULL,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`status` enum('1','0') NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
);

2. Create a folder named angularjs-crud in htdocs folder.

3. Copy bootstrap.min.css, jquery.min.js, bootstrap.min.js and angular.min.js files.

4. Create a PHP file named database.php in angularjs-crud folder and add database connection code.

<?php
class DB {
   public $db;
   /* Connect to the database and return db connection */ 
   public function __construct()
   { 
       if(!isset($this->db)){
           // Connect to the database
           $this->db = new mysqli("localhost","root","","angularjs");
       }
    }
}

?>



5. Search and copy image icons of edit, delete and down arrow into angularjs-crud folder.

6. Copy required files in angularJS folder. Create a file named index.html. Link necessary files and add CSS code.


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Angularjs CRUD operations</title>
<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>
<style type="text/css"> 
/* 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%;} 
.myclass {margin-bottom:30px; color:blue; } 
.space {margin-right:20px;} 
.alert {width: 50%; border-radius: 0;margin-top: 10px;margin-left: 10px;} 
</style> 
</head> 
<body> 
</body> 
</html> 

7. Create a new file named action.php and write PHP code to read user data.


<?php include 'database.php'; 
     $db = new DB(); 
     if(isset($_REQUEST['type']) && !empty($_REQUEST['type']))
     {
         $type = $_REQUEST['type']; switch($type)
         {
             case "view":
             $query = "Select * from users";
             $data['records'] = $db->getRows($query); echo json_encode($data); break;
             case "add": break;
             case "edit": break;
             case "delete": break;
             default:
             echo '{"status":"INVALID"}';
         }
     }

     ?>

8. Now add code in database.php file to execute select query.


public function getRows($selectQuery)
{
    $result = $this->db->query($selectQuery); 
    if($result->num_rows>0)
    {
        while($row= $result->fetch_assoc())
        {
            $data[] = $row;
        }
    }
    return !empty($data)?$data:false;
}



9. Replace body part of index.html by following code to read data from users table.


<body ng-app="crudApp">
<div class="container" ng-controller="userController" ng-init="getRecords()">
<div class="row">
<center>
<h2 class="myclass">AngularJS, PHP and MySQL Tutorial</h2>
<h4 class="myclass">AngularJS CRUD Operation</h4>
</center>
<div class="panel panel-default users-content">
<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>
<img src="edit.gif" class="space" ng-click="editUser(user)" />
<img src="delete.png" ng-click="deleteUser(user)" /> </td> </tr>
</table>
</div>
</div>
</div>
</body>

10. Add angularjs code into the head section of index.html to read existing records.


<script>
//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)
      {
          $scope.users = response.records;
      });
      }); 
};
</script>

11. Add some records into users table manually and run index.html file from server.

12. Add the following code of angularjs form into index.html file before table tag to add or edit user data.


<div class="panel-heading">Users <img src='arrow.jpg' height="15" width="15" onclick="$('.formData').slideToggle();" />
</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" novalidate>
<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" type="email" ngmodel="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" ngclick="addUser()">Add User</a>
<a href="javascript:void(0);" class="btn btn-success" ng-hide="!tempUserData.id" ngclick="updateUser()">Update User</a>
</form>
</div>

13. Add angularjs code for inserting or editing new user data into head section.


//function to add user data
$scope.addUser = function() {
$scope.saveUser('add');
};
// function to insert or update user data to the database
$scope.saveUser = function(type) {
var data = $.param({
'udata':$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.getRecords();
$scope.userForm.$setPristine();
$scope.tempUserData = {};
$('.formData').slideUp();
$scope.messageSuccess(response.msg);
}
else {
alert(response.status);
$scope.messageError(response.msg);
}

});

};

14. Add code to display success or failure message.


// function to display success message
$scope.messageSuccess = function(msg)
{
$('.alert-success > p').html(msg);
$('.alert-success').show();
$('.alert-success').delay(2000).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(3000).slideUp(function() { $('.alert-danger > p').html('');
});
};

15. Add PHP code in action.php to insert user data into MYSQL


if(isset($_POST['udata']['name']) && isset($_POST['udata']['email']) && isset($_POST['udata']['phone'])){
$name=$_POST['udata']['name'];
$email=$_POST['udata']['email'];
$phone=$_POST['udata']['phone'];
$query = "insert into users set id=NULL, name='$name', email='$email', phone='$phone'";
$result=$db->insert($query);
if($result){
$data['status'] = 'OK';
$data['msg'] = 'User data has been added successfully.';
}
else{
$data['status'] = 'Error';
$data['msg'] = 'Some problem occurred, please try again.';
}
}
else
{
$data['status'] = 'Error';
$data['msg'] = 'Some problem occurred, please try again666.';
}
echo json_encode($data);

16. Now add code in database.php file to execute insert query.
/* Insert data into the database */


public function insert($insertQuery)
{
     $result = $this->db->query($insertQuery);
     if($result)
        return true;
     else
        return false;
}

17. Run index.html file from server and try to insert any records.

18. Add angularjs code to edit and update data


//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');
};

19. Add code in action.php to handle update request


if(isset($_POST['udata']['name']) && isset($_POST['udata']['email']) && isset($_POST['udata']['phone'])) { $id=$_POST['udata']['id'];
$name=$_POST['udata']['name'];
$email=$_POST['udata']['email'];
$phone=$_POST['udata']['phone'];
$query = "update users set name='$name', email='$email', phone='$phone' where id=$id";
$result=$db->update($query); if($result) {
$data['status'] = 'OK';
$data['msg'] = 'User data has been updated successfully.';
}
else {
$data['status'] = 'Error';
$data['msg'] = 'Some problem occurred, please try again.';
} }
else {
$data['status'] = 'Error';
$data['msg'] = 'Some problem occurred, please try again.';
}
echo json_encode($data);

20. Add code in database.php to execute update query.


/* Update data into the database */
public function update($updateQuery)
{
$result = $this->db->query($updateQuery); 
if($result) 
return true; 
else
return false;
}

21. Add angularjs code into index.html file for sending delete request.


//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);
}
});
}
};

22. Add code in action.php to handle delete request


if(!empty($_POST['id'])) {
$id = $_POST['id'];
$query = "Delete from users where id =$id";
$delete = $db->delete($query); if($delete) {
$data['status'] = 'OK';
$data['msg'] = 'User data has been deleted successfully.';
}
else {
$data['status'] = 'Error';
$data['msg'] = 'Some problem occurred, please try again.';
} 
} 
else {
$data['status'] = 'Error';
$data['msg'] = 'Some problem occurred, please try again.';
}
echo json_encode($data);

23. Add code in database.php to execute delete query


/* Delete data from the database */ public function delete($deleteQuery)
{
$result = $this->db->query($deleteQuery);
if($result) return true; else
return false;
}

Your angularjs app of CRUD operation is ready now. Good Luck.
Check the following video to see the steps.

 

Exit mobile version