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

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. 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-option) using PHP/MySQLi</title>
  5.     <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  6.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  7. </head>
  8. <body ng-controller="myController">
  9. <div class="container">
  10.     <h1 class="page-header text-center">AngularJS Save Selected Options (ng-option) 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" ng-options="f.fruitname for f in fruits" class="form-control" placeholder="Select Fruit" required>
  16.                                         <option value="">-- Select Fruit --</option>
  17.                                 </select>
  18.                                 <p style="margin-top:10px;"><b>Fruit selected:</b> {{selectedFruit.fruitname}}</p>
  19.                                 <hr>
  20.                                 <h3>Select Vegetable</h3>
  21.                                 <select ng-model="selectedVegetable" ng-options="v.vegetablename for v in vegetables" class="form-control" required>
  22.                                         <option value="">-- Select Vegetable --</option>
  23.                                 </select>
  24.                                 <p style="margin-top:10px;"><b>Vegetable selected:</b> {{selectedVegetable.vegetablename}}</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.                                 <thead>
  41.                                         <tr>
  42.                                                 <th>Purchase Date</th>
  43.                                                 <th>Fruit</th>
  44.                                                 <th>Vegetable</th>
  45.                                         <tr>
  46.                                 </thead>
  47.                                 <tbody>
  48.                                         <tr ng-repeat="purchase in purchases">
  49.                                                 <td>{{ purchase.date_purchase | dateToISO | date:'MMMM dd, yyyy - hh:mm a' }}</td>
  50.                                                 <td>{{ purchase.fruitname }}</td>
  51.                                                 <td>{{ purchase.vegetablename }}</td>
  52.                                         </tr>
  53.                                 </tbody>
  54.                         </table>
  55.                 </div>
  56.         </div>
  57. </div>
  58. <script src="angular.js"></script>
  59. </body>
  60. </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.         $scope.newPurchase = [];
  21.  
  22.         //inserting our selected object
  23.         $scope.newPurchase.push($scope.selectedVegetable);
  24.         $scope.newPurchase.push($scope.selectedFruit);
  25.  
  26.         $http.post('purchase.php', $scope.newPurchase)
  27.         .success(function(data){
  28.             if(data.error){
  29.                 $scope.error = true;
  30.                 $scope.success = false;
  31.                 $scope.message = data.message;
  32.             }
  33.             else{
  34.                 $scope.success = true;
  35.                 $scope.error = false;
  36.                 $scope.message = data.message;
  37.                 $scope.fetchpurchase();
  38.             }
  39.             console.log(data);
  40.             });
  41.     }
  42.  
  43.     $scope.clearMsg = function(){
  44.         $scope.success = false;
  45.         $scope.error = false;
  46.     }
  47. });
  48.  
  49. //convert mysql data to angular date format
  50. app.filter('dateToISO', function() {
  51.   return function(input) {
  52.     input = new Date(input).toISOString();
  53.     return input;
  54.   };
  55. });

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.         //note that the first object our $scope.newPurchase is vegetable
  10.         $vegetable = $data[0];
  11.         $vid = $vegetable->vegetableid;
  12.  
  13.         //getting fruitid
  14.         $fruit = $data[1];
  15.         $fid = $fruit->fruitid;
  16.        
  17.         $sql = "INSERT INTO purchases (vegetableid, fruitid, date_purchase) VALUES ('$vid', '$fid', NOW())";
  18.         $query = $conn->query($sql);
  19.  
  20.         if($query){
  21.                 $out['message'] = "Purchase added Successfully";
  22.         }
  23.         else{
  24.                 $out['error'] = true;
  25.                 $out['messge'] = "Cannot add Purchase";
  26.         }
  27.  
  28.         echo json_encode($out);
  29.        
  30. ?>

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. ?>
That ends this tutorial. Happy Coding :)

Add new comment