AngularJS Save Selected Options (ng-repeat) using PHP/MySQLi

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

Getting Started

I've used CDN for Bootstrap and Angular JS in this tutorial so you need internet connection for them to work.

In the previous tutorial, we have tackled on how to Dynamically Add Options which we discuss that options using ng-repeat return a string. In this tutorial, we are going to save this selected option.

Creating our Database

First, we're gonna create our database and insert data for our options.

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 `fruits` (
  2. `fruitid` int(11) NOT NULL AUTO_INCREMENT,
  3. `fruitname` varchar(30) NOT NULL,
  4. PRIMARY KEY(`fruitid`)
  5.  
  6. CREATE TABLE `vegetables` (
  7. `vegetableid` int(11) NOT NULL AUTO_INCREMENT,
  8. `vegetablename` varchar(30) NOT NULL,
  9. PRIMARY KEY(`vegetableid`)
  10.  
  11. CREATE TABLE `purchases` (
  12. `purchaseid` int(11) NOT NULL AUTO_INCREMENT,
  13. `vegetableid` int(11) NOT NULL,
  14. `fruitid` int(11) NOT NULL,
  15. PRIMARY KEY(`purchaseid`)
  16. `date_purchase` datetime NOT NULL
  1. INSERT INTO `fruits` (`fruitid`, `fruitname`) VALUES
  2. (1, 'Apple'),
  3. (2, 'Orange'),
  4. (3, 'Strawberry'),
  5. (4, 'Pineapple'),
  6. (5, 'Star Apple'),
  7. (7, 'Banana'),
  8. (8, 'Lemon'),
  9. (9, 'Mango'),
  10. (10, 'Guava'),
  11. (11, 'Watermelon'),
  12. (12, 'Avocado'),
  13. (13, 'Apricot'),
  14. (14, 'Blackberry'),
  15. (15, 'Coconut'),
  16. (16, 'Melon'),
  17. (17, 'Papaya'),
  18. (18, 'Peach'),
  19. (19, 'Pomelo'),
  20. (20, 'Grapes');
  21.  
  22. INSERT INTO `purchases` (`purchaseid`, `vegetableid`, `fruitid`, `date_purchase`) VALUES
  23. (1, 9, 4, '2018-01-11 14:21:16'),
  24. (2, 8, 10, '2018-01-11 14:42:57'),
  25. (3, 2, 7, '2018-01-11 15:22:34'),
  26. (4, 6, 3, '2018-01-11 15:27:44'),
  27. (5, 10, 5, '2018-01-11 15:28:29'),
  28. (6, 4, 17, '2018-01-11 15:30:57'),
  29. (7, 9, 5, '2018-01-11 15:37:16'),
  30. (8, 4, 8, '2018-01-11 15:39:10');

database sql

index.html

This is our index which contains our form and table.

  1. <!DOCTYPE html>
  2. <html lang="en" ng-app="app">
  3. <meta charset="utf-8">
  4. <title>AngularJS Save Selected Options (ng-repeat) using 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. <script src="<a href="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  7. </head>
  8. <body" rel="nofollow">http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></s...</a> ng-controller="myController">
  9. <div class="container">
  10. <h1 class="page-header text-center">AngularJS Save Selected Options (ng-repeat) using PHP/MySQLi</h1>
  11. <div class="row">
  12. <div class="col-md-3 col-md-offset-1" ng-init="fetch()">
  13. <h3>Select Fruit</h3>
  14. <form name="purchaseForm" novalidate>
  15. <select ng-model="selectedFruit" class="form-control">
  16. <option ng-repeat="fruit in fruits" value="{{fruit.fruitid}}">{{fruit.fruitname}}</option>
  17. </select>
  18. <p style="margin-top:10px;"><b>Fruit selected (ID):</b> {{selectedFruit}}</p>
  19. <hr>
  20. <h3>Select Vegetable</h3>
  21. <select ng-model="selectedVegetable" class="form-control">
  22. <option ng-repeat="vegetable in vegetables" value="{{vegetable.vegetableid}}">{{vegetable.vegetablename}}</option>
  23. </select>
  24. <p style="margin-top:10px;"><b>Vegetable selected (ID):</b> {{selectedVegetable}}</p>
  25. <hr>
  26. <button type="button" class="btn btn-primary" ng-click="purchase()" ng-disabled="purchaseForm.$invalid">Purchase</button>
  27. </form>
  28. <div class="alert alert-success text-center" ng-show="success" style="margin-top: 20px">
  29. <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">&times;</span></button>
  30. {{ message }}
  31. </div>
  32. <div class="alert alert-danger text-center" ng-show="error" style="margin-top: 20px">
  33. <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">&times;</span></button>
  34. {{ message }}
  35. </div>
  36. </div>
  37. <div class="col-md-7" ng-init="fetchpurchase()">
  38. <h3>Purchase Table</h3>
  39. <table class="table table-bordered table-striped">
  40. <tr>
  41. <th>Purchase Date</th>
  42. <th>Fruit</th>
  43. <th>Vegetable</th>
  44. <tr>
  45. </thead>
  46. <tr ng-repeat="purchase in purchases">
  47. <td>{{ purchase.date_purchase | dateToISO | date:'MMMM dd, yyyy - hh:mm a' }}</td>
  48. <td>{{ purchase.fruitname }}</td>
  49. <td>{{ purchase.vegetablename }}</td>
  50. </tr>
  51. </tbody>
  52. </table>
  53. </div>
  54. </div>
  55. </div>
  56. <script src="angular.js"></script>
  57. </body>
  58. </html>

angular.js

This contains our angular.js scripts.

  1. var app = angular.module('app', []);
  2. app.controller('myController', function($scope, $http){
  3. $scope.success = false;
  4. $scope.error = false;
  5.  
  6. $scope.fetch = function(){
  7. $http.get('fetch.php').success(function(data){
  8. $scope.fruits = data.fruits;
  9. $scope.vegetables = data.vegetables;
  10. });
  11. }
  12.  
  13. $scope.fetchpurchase = function(){
  14. $http.get('fetchpurchase.php').success(function(data){
  15. $scope.purchases = data;
  16. });
  17. }
  18.  
  19. $scope.purchase = function(){
  20. $http.post('purchase.php', {
  21. 'fruit': $scope.selectedFruit,
  22. 'vegetable': $scope.selectedVegetable
  23. })
  24. .success(function(data){
  25. if(data.error){
  26. $scope.error = true;
  27. $scope.success = false;
  28. $scope.message = data.message;
  29. }
  30. else{
  31. $scope.success = true;
  32. $scope.error = false;
  33. $scope.message = data.message;
  34. $scope.fetchpurchase();
  35. }
  36. console.log(data);
  37. });
  38. }
  39.  
  40. $scope.clearMsg = function(){
  41. $scope.success = false;
  42. $scope.error = false;
  43. }
  44. });
  45.  
  46. //convert mysql data to angular date format
  47. app.filter('dateToISO', function() {
  48. return function(input) {
  49. input = new Date(input).toISOString();
  50. return input;
  51. };
  52. });

fetch.php

Our PHP api that fetches data from our MySQL database.

  1. <?php
  2. $conn = new mysqli('localhost', 'root', '', 'angular');
  3.  
  4. $output = array();
  5.  
  6. //for fruits
  7. $sql = "SELECT * FROM fruits";
  8. $fquery=$conn->query($sql);
  9. while($frow=$fquery->fetch_array()){
  10. $output['fruits'][] = $frow;
  11. }
  12.  
  13. //for vegetables
  14. $sql = "SELECT * FROM vegetables";
  15. $vquery = $conn->query($sql);
  16. while($vrow=$vquery->fetch_array()){
  17. $output['vegetables'][] = $vrow;
  18. }
  19.  
  20. echo json_encode($output);
  21. ?>

purchase.php

This is our PHP api in adding the selected options into our MySQL 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);
  7.  
  8. //getting vegetableid
  9. $vid = $data->vegetable;
  10.  
  11. //getting fruitid
  12. $fid = $data->fruit;
  13.  
  14. $sql = "INSERT INTO purchases (vegetableid, fruitid, date_purchase) VALUES ('$vid', '$fid', NOW())";
  15. $query = $conn->query($sql);
  16.  
  17. if($query){
  18. $out['message'] = "Purchase added Successfully";
  19. }
  20. else{
  21. $out['error'] = true;
  22. $out['messge'] = "Cannot add Purchase";
  23. }
  24.  
  25. echo json_encode($out);
  26.  
  27. ?>

fetchpurchase.php

Lastly, this is our another PHP api that fetches data from our MySQL Database.

  1. <?php
  2. $conn = new mysqli('localhost', 'root', '', 'angular');
  3.  
  4. $output = array();
  5.  
  6. $sql = "SELECT * FROM purchases LEFT JOIN vegetables ON vegetables.vegetableid=purchases.vegetableid LEFT JOIN fruits ON fruits.fruitid=purchases.fruitid ORDER BY date_purchase DESC";
  7. $query = $conn->query($sql);
  8. while($row = $query->fetch_array()){
  9. $output[] = $row;
  10. }
  11.  
  12. echo json_encode($output);
  13.  
  14. ?>

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.