Table of Contents
Tutorial: Save Selected Options using AngularJS and PHP/MySQLi with Source Code
Getting Started on Save Selected Options using AngularJS
This is a tutorial on Save Selected Options using AngularJS with PHP and MySQLi. I’ve used CDN for Bootstrap and Angular JS in this tutorial, so you need an 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.
CREATE TABLE `fruits` ( `fruitid` int(11) NOT NULL AUTO_INCREMENT, `fruitname` varchar(30) NOT NULL, PRIMARY KEY(`fruitid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `vegetables` ( `vegetableid` int(11) NOT NULL AUTO_INCREMENT, `vegetablename` varchar(30) NOT NULL, PRIMARY KEY(`vegetableid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `purchases` ( `purchaseid` int(11) NOT NULL AUTO_INCREMENT, `vegetableid` int(11) NOT NULL, `fruitid` int(11) NOT NULL, PRIMARY KEY(`purchaseid`) `date_purchase` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `fruits` (`fruitid`, `fruitname`) VALUES (1, 'Apple'), (2, 'Orange'), (3, 'Strawberry'), (4, 'Pineapple'), (5, 'Star Apple'), (7, 'Banana'), (8, 'Lemon'), (9, 'Mango'), (10, 'Guava'), (11, 'Watermelon'), (12, 'Avocado'), (13, 'Apricot'), (14, 'Blackberry'), (15, 'Coconut'), (16, 'Melon'), (17, 'Papaya'), (18, 'Peach'), (19, 'Pomelo'), (20, 'Grapes'); INSERT INTO `purchases` (`purchaseid`, `vegetableid`, `fruitid`, `date_purchase`) VALUES (1, 9, 4, '2018-01-11 14:21:16'), (2, 8, 10, '2018-01-11 14:42:57'), (3, 2, 7, '2018-01-11 15:22:34'), (4, 6, 3, '2018-01-11 15:27:44'), (5, 10, 5, '2018-01-11 15:28:29'), (6, 4, 17, '2018-01-11 15:30:57'), (7, 9, 5, '2018-01-11 15:37:16'), (8, 4, 8, '2018-01-11 15:39:10');
index.html
This is an index which contains a form and table.
!DOCTYPE html> <html lang="en" ng-app="app"> <head> <meta charset="utf-8"> <title>AngularJS Save Selected Options (ng-repeat) using PHP/MySQLi</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> </head> <body ng-controller="myController"> <div class="container"> <h1 class="page-header text-center">AngularJS Save Selected Options (ng-repeat) using PHP/MySQLi</h1> <div class="row"> <div class="col-md-3 col-md-offset-1" ng-init="fetch()"> <h3>Select Fruit</h3> <form name="purchaseForm" novalidate> <select ng-model="selectedFruit" class="form-control"> <option ng-repeat="fruit in fruits" value="{{fruit.fruitid}}">{{fruit.fruitname}}</option> </select> <p style="margin-top:10px;"><b>Fruit selected (ID):</b> {{selectedFruit}}</p> <hr> <h3>Select Vegetable</h3> <select ng-model="selectedVegetable" class="form-control"> <option ng-repeat="vegetable in vegetables" value="{{vegetable.vegetableid}}">{{vegetable.vegetablename}}</option> </select> <p style="margin-top:10px;"><b>Vegetable selected (ID):</b> {{selectedVegetable}}</p> <hr> <button type="button" class="btn btn-primary" ng-click="purchase()" ng-disabled="purchaseForm.$invalid">Purchase</button> </form> <div class="alert alert-success text-center" ng-show="success" style="margin-top: 20px"> <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">×</span></button> {{ message }} </div> <div class="alert alert-danger text-center" ng-show="error" style="margin-top: 20px"> <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">×</span></button> {{ message }} </div> </div> <div class="col-md-7" ng-init="fetchpurchase()"> <h3>Purchase Table</h3> <table class="table table-bordered table-striped"> <thead> <tr> <th>Purchase Date</th> <th>Fruit</th> <th>Vegetable</th> <tr> </thead> <tbody> <tr ng-repeat="purchase in purchases"> <td>{{ purchase.date_purchase | dateToISO | date:'MMMM dd, yyyy - hh:mm a' }}</td> <td>{{ purchase.fruitname }}</td> <td>{{ purchase.vegetablename }}</td> </tr> </tbody> </table> </div> </div> </div> <script src="angular.js"></script> </body> </html>
angular.js
This contains an angular.js scripts.
var app = angular.module('app', []); app.controller('myController', function($scope, $http){ $scope.success = false; $scope.error = false; $scope.fetch = function(){ $http.get('fetch.php').success(function(data){ $scope.fruits = data.fruits; $scope.vegetables = data.vegetables; }); } $scope.fetchpurchase = function(){ $http.get('fetchpurchase.php').success(function(data){ $scope.purchases = data; }); } $scope.purchase = function(){ $http.post('purchase.php', { 'fruit': $scope.selectedFruit, 'vegetable': $scope.selectedVegetable }) .success(function(data){ if(data.error){ $scope.error = true; $scope.success = false; $scope.message = data.message; } else{ $scope.success = true; $scope.error = false; $scope.message = data.message; $scope.fetchpurchase(); } console.log(data); }); } $scope.clearMsg = function(){ $scope.success = false; $scope.error = false; } }); //convert mysql data to angular date format app.filter('dateToISO', function() { return function(input) { input = new Date(input).toISOString(); return input; }; });
fetch.php
a PHP api that fetches data from a MySQL database.
<?php $conn = new mysqli('localhost', 'root', '', 'angular'); $output = array(); //for fruits $sql = "SELECT * FROM fruits"; $fquery=$conn->query($sql); while($frow=$fquery->fetch_array()){ $output['fruits'][] = $frow; } //for vegetables $sql = "SELECT * FROM vegetables"; $vquery = $conn->query($sql); while($vrow=$vquery->fetch_array()){ $output['vegetables'][] = $vrow; } echo json_encode($output); ?>
purchase.php
This is a PHP api in adding the selected options into an MySQL Database.
<?php $conn = new mysqli('localhost', 'root', '', 'angular'); $data = json_decode(file_get_contents("php://input")); $out = array('error' => false); //getting vegetableid $vid = $data->vegetable; //getting fruitid $fid = $data->fruit; $sql = "INSERT INTO purchases (vegetableid, fruitid, date_purchase) VALUES ('$vid', '$fid', NOW())"; $query = $conn->query($sql); if($query){ $out['message'] = "Purchase added Successfully"; } else{ $out['error'] = true; $out['messge'] = "Cannot add Purchase"; } echo json_encode($out); ?>
fetchpurchase.php
Lastly, this is our another PHP api that fetches data from our MySQL Database.
<?php $conn = new mysqli('localhost', 'root', '', 'angular'); $output = array(); $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"; $query = $conn->query($sql); while($row = $query->fetch_array()){ $output[] = $row; } echo json_encode($output); ?>
This tutorial is on how to Save Selected Options using AngularJS. Happy Coding!