AngularJS CRUD using Ui-Router in PHP/MySQLi

Submitted by: 
Language: 
Visitors have accessed this post 2364 times.

Getting Started

I've used CDN for Bootstrap, Angular JS and Ui-Router so you need internet connection for them to work.

Creating our Database

First, we're going to create our MySQL database.

1. Open phpMyAdmin.
2. Click databases, create a database and name it as angular.
3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.

  1. CREATE TABLE `members` (
  2. `memid` int(11) NOT NULL AUTO_INCREMENT,
  3. `firstname` varchar(30) NOT NULL,
  4. `lastname` varchar(30) NOT NULL,
  5. `address` text NOT NULL,
  6. PRIMARY KEY(`memid`)

database sql

index.html

This is the main view of our app and the place where we declare all our dependencies.

  1. <!DOCTYPE html>
  2. <html lang="en" ng-app="app">
  3. <meta charset="utf-8">
  4. <title>AngularJS CRUD using Ui-Router in PHP/MySQLi</title>
  5. <link href="<a href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"" rel="nofollow">https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"</a> rel="stylesheet">
  6. <link href="<a href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"" rel="nofollow">https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min....</a> rel="stylesheet">
  7. <script src="<a href="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  8. " rel="nofollow">http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></s...</a> <script src="<a href="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
  9. </head>
  10. <div" rel="nofollow">https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-u...</a> class="container">
  11. <h1 class="page-header text-center">AngularJS CRUD using Ui-Router in PHP/MySQLi</h1>
  12. <!-- this is where we render our view -->
  13. <div ui-view></div>
  14. </div>
  15. <!-- main script -->
  16. <script src="js/app.js"></script>
  17. <!-- controllers -->
  18. <script src="js/controllers/homeController.js"></script>
  19. <script src="js/controllers/addController.js"></script>
  20. <script src="js/controllers/editController.js"></script>
  21. <script src="js/controllers/deleteController.js"></script>
  22. <!-- services -->
  23. <script src="js/services/memberService.js"></script>
  24. </body>
  25. </html>

app.js

This is the main angular script of our app.

  1. var app = angular.module('app', ['ui.router']);
  2.  
  3. app.config(function($stateProvider, $urlRouterProvider) {
  4.  
  5. $urlRouterProvider.otherwise('/home');
  6. $stateProvider
  7. .state('home', {
  8. url: '/home',
  9. templateUrl: 'partials/home.html',
  10. controller: 'homeCtrl'
  11. })
  12. .state('add', {
  13. url: '/add',
  14. templateUrl: 'partials/add.html',
  15. controller: 'addCtrl'
  16. })
  17. .state('edit', {
  18. url: '/edit/{member:json}',
  19. templateUrl: 'partials/edit.html',
  20. controller: 'editCtrl'
  21. })
  22. .state('delete', {
  23. url: '/delete/{member:json}',
  24. templateUrl: 'partials/delete.html',
  25. controller: 'deleteCtrl'
  26. })
  27.  
  28. });

memberService.js

This is the service that we created to handle our members and request.

  1. 'use strict';
  2.  
  3. app.factory('memberService', function($http){
  4. return{
  5. read: function(){
  6. var read = $http.get('api/read.php');
  7. return read;
  8. },
  9. create: function(member){
  10. var add = $http.post('api/add.php', member);
  11. return add;
  12. },
  13. update: function(member){
  14. var edit = $http.post('api/edit.php', member);
  15. return edit;
  16. },
  17. delete: function(member){
  18. var del = $http.post('api/delete.php', member);
  19. return del;
  20. }
  21. }
  22. });

homeController.js

This is our controller for home.html.

  1. 'use strict';
  2.  
  3. app.controller('homeCtrl', ['$scope', 'memberService', function($scope, memberService){
  4. //fetch members
  5. $scope.fetch = function(){
  6. var members = memberService.read();
  7. members.then(function(response){
  8. $scope.members = response.data;
  9. });
  10. }
  11.  
  12. }]);

addController.js

This the controller for our add.html.

  1. 'use strict';
  2.  
  3. app.controller('addCtrl', ['$scope', 'memberService', '$location', function($scope, memberService, $location){
  4. $scope.error = false;
  5. //add member
  6. $scope.add = function(){
  7. var addmember = memberService.create($scope.member);
  8. addmember.then(function(response){
  9. if(response.data.error){
  10. $scope.error = true;
  11. $scope.message = response.data.message;
  12. }
  13. else{
  14. console.log(response);
  15. $location.path('home');
  16. }
  17. });
  18. }
  19.  
  20. }]);

editController.js

This is our controller for edit.html.

  1. 'use strict';
  2.  
  3. app.controller('editCtrl', ['$scope', 'memberService', '$location', '$stateParams', function($scope, memberService, $location, $stateParams){
  4. $scope.error = false;
  5. $scope.updatedmember = $stateParams.member;
  6.  
  7. //edit member
  8. $scope.update = function(){
  9. var updatemember = memberService.update($scope.updatedmember);
  10. updatemember.then(function(response){
  11. console.log(response);
  12. if(response.data.error){
  13. $scope.error = true;
  14. $scope.message = response.data.message;
  15. }
  16. else{
  17. console.log(response);
  18. $location.path('home');
  19. }
  20. });
  21. }
  22.  
  23. }]);

deleteController.js

This is our controller for delete.html.

  1. 'use strict';
  2.  
  3. app.controller('deleteCtrl', ['$scope', 'memberService', '$location', '$stateParams', function($scope, memberService, $location, $stateParams){
  4. $scope.error = false;
  5. $scope.deletemember = $stateParams.member;
  6.  
  7. //delete member
  8. $scope.delete = function(){
  9. var dmember = memberService.delete($scope.deletemember);
  10. dmember.then(function(response){
  11. if(response.data.error){
  12. $scope.error = true;
  13. $scope.message = response.data.message;
  14. }
  15. else{
  16. console.log(response);
  17. $location.path('home');
  18. }
  19. });
  20. }
  21. }]);

home.html

As per our ui-router, this is considered to be our index view.

  1. <div class="row" ng-init="fetch()">
  2. <div class="col-md-8 col-md-offset-2">
  3. <button href="" class="btn btn-primary" ui-sref="add"><i class="fa fa-plus"></i> Add New</button>
  4. <table class="table table-bordered table-striped" style="margin-top:10px;">
  5. <tr>
  6. <th>Firstname</th>
  7. <th>Lastname</th>
  8. <th>Address</th>
  9. <th>Action</th>
  10. </tr>
  11. </thead>
  12. <tr ng-repeat="member in members">
  13. <td>{{ member.firstname }}</td>
  14. <td>{{ member.lastname }}</td>
  15. <td>{{ member.address }}</td>
  16. <td>
  17. <button type="button" class="btn btn-success" ui-sref="edit({member: member})"><i class="fa fa-edit"></i> Edit</button>
  18. <button type="button" class="btn btn-danger" ui-sref="delete({member: member})"> <i class="fa fa-trash"></i> Delete</button>
  19. </td>
  20. </tr>
  21. </tbody>
  22. </table>
  23. </div>
  24. </div>

add.html

This contains our add new form.

  1. <div class="row">
  2. <div class="col-sm-4 col-sm-offset-4">
  3. <div class="alert alert-danger text-center" ng-show="error">
  4. <button type="button" class="close" ng-click="clear()"><span aria-hidden="true">&times;</span></button>
  5. <i class="fa fa-warning"></i> {{ message }}
  6. </div>
  7. <div class="panel panel-default">
  8. <div class="panel-body">
  9. <h3 class="text-center">Add Form</h3>
  10. <div class="form-group">
  11. <label>Firstname:</label>
  12. <input type="text" class="form-control" ng-model="member.firstname">
  13. </div>
  14. <div class="form-group">
  15. <label>Lastname:</label>
  16. <input type="text" class="form-control" ng-model="member.lastname">
  17. </div>
  18. <div class="form-group">
  19. <label>Address:</label>
  20. <input type="text" class="form-control" ng-model="member.address">
  21. </div>
  22. <button type="button" class="btn btn-primary" ng-click="add()"><i class="fa fa-save"></i> Save</button>
  23. <button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
  24. </div>
  25. </div>
  26. </div>
  27. </div>

edit.html

This contains our edit form.

  1. <div class="row">
  2. <div class="col-sm-4 col-sm-offset-4">
  3. <div class="alert alert-danger text-center" ng-show="error">
  4. <button type="button" class="close" ng-click="clear()"><span aria-hidden="true">&times;</span></button>
  5. <i class="fa fa-warning"></i> {{ message }}
  6. </div>
  7. <div class="panel panel-default">
  8. <div class="panel-body">
  9. <h3 class="text-center">Edit Form</h3>
  10. <div class="form-group">
  11. <label>Firstname:</label>
  12. <input type="text" class="form-control" ng-model="updatedmember.firstname">
  13. </div>
  14. <div class="form-group">
  15. <label>Lastname:</label>
  16. <input type="text" class="form-control" ng-model="updatedmember.lastname">
  17. </div>
  18. <div class="form-group">
  19. <label>Address:</label>
  20. <input type="text" class="form-control" ng-model="updatedmember.address">
  21. </div>
  22. <button type="button" class="btn btn-success" ng-click="update()"><i class="fa fa-check-square-o"></i> Update</button>
  23. <button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
  24. </div>
  25. </div>
  26. </div>
  27. </div>

delete.html

This is delete confirmation view.

  1. <div class="row">
  2. <div class="col-sm-4 col-sm-offset-4">
  3. <div class="alert alert-danger text-center" ng-show="error">
  4. <button type="button" class="close" ng-click="clear()"><span aria-hidden="true">&times;</span></button>
  5. <i class="fa fa-warning"></i> {{ message }}
  6. </div>
  7. <div class="panel panel-default">
  8. <div class="panel-body">
  9. <h4 class="text-center">Are you sure you want to delete</h4>
  10. <h3 class="text-center">{{ deletemember.firstname + ' ' + deletemember.lastname }}</h3><br>
  11. <button type="button" class="btn btn-danger" ng-click="delete()"><i class="fa fa-trash"></i> Update</button>
  12. <button type="button" class="btn btn-default pull-right" ui-sref="home"><i class="fa fa-arrow-left"></i> Back</button>
  13. </div>
  14. </div>
  15.  
  16. </div>
  17. </div>

read.php

This is our PHP api the fetches data from our database.

  1. <?php
  2. $conn = new mysqli('localhost', 'root', '', 'angular');
  3.  
  4. $out = array();
  5. $sql = "SELECT * FROM members";
  6. $query=$conn->query($sql);
  7. while($row=$query->fetch_array()){
  8. $out[] = $row;
  9. }
  10.  
  11. echo json_encode($out);
  12. ?>

add.php

Our PHP api that adds new data to our database.

  1. <?php
  2. $conn = new mysqli('localhost', 'root', '', 'angular');
  3.  
  4. $data = json_decode(file_get_contents("php://input"));
  5.  
  6. $out = array('error' => false, 'firstname' => false, 'lastname' => false, 'address' => false);
  7.  
  8. $firstname = $data->firstname;
  9. $lastname = $data->lastname;
  10. $address = $data->address;
  11.  
  12. if(empty($firstname)){
  13. $out['firstname'] = true;
  14. $out['message'] = 'Firstname is required';
  15. }
  16. elseif(empty($lastname)){
  17. $out['lastname'] = true;
  18. $out['message'] = 'Lastname is required';
  19. }
  20. elseif(empty($address)){
  21. $out['address'] = true;
  22. $out['message'] = 'Address is required';
  23. }
  24. else{
  25. $sql = "INSERT INTO members (firstname, lastname, address) VALUES ('$firstname', '$lastname', '$address')";
  26. $query = $conn->query($sql);
  27.  
  28. if($query){
  29. $out['message'] = 'Member Added Successfully';
  30. }
  31. else{
  32. $out['error'] = true;
  33. $out['message'] = 'Cannot Add Member';
  34. }
  35. }
  36.  
  37. echo json_encode($out);
  38. ?>

edit.php

Our PHP api that updates our selected data.

  1. <?php
  2. $conn = new mysqli('localhost', 'root', '', 'angular');
  3.  
  4. $data = json_decode(file_get_contents("php://input"));
  5.  
  6. $out = array('error' => false);
  7.  
  8. $firstname = $data->firstname;
  9. $lastname = $data->lastname;
  10. $address = $data->address;
  11. $memid = $data->memid;
  12.  
  13. $sql = "UPDATE members SET firstname = '$firstname', lastname = '$lastname', address = '$address' WHERE memid = '$memid'";
  14. $query = $conn->query($sql);
  15.  
  16. if($query){
  17. $out['message'] = 'Member updated Successfully';
  18. }
  19. else{
  20. $out['error'] = true;
  21. $out['message'] = 'Cannot update Member';
  22. }
  23.  
  24. echo json_encode($out);
  25. ?>

delete.php

Lastly, this is our PHP api that delete our selected data.

  1. <?php
  2. $conn = new mysqli('localhost', 'root', '', 'angular');
  3.  
  4. $data = json_decode(file_get_contents("php://input"));
  5.  
  6. $out = array('error' => false);
  7.  
  8. $memid = $data->memid;
  9.  
  10. $sql = "DELETE FROM members WHERE memid = '$memid'";
  11. $query = $conn->query($sql);
  12.  
  13. if($query){
  14. $out['message'] = 'Member deleted Successfully';
  15. }
  16. else{
  17. $out['error'] = true;
  18. $out['message'] = 'Cannot delete Member';
  19. }
  20.  
  21. echo json_encode($out);
  22. ?>

That ends this tutorial. Happy Coding :)


Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

good working software for bigner

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.