AngularJS Select - Dynamically add Options using PHP/MySQLi
Submitted by nurhodelta_17 on Wednesday, January 10, 2018 - 19:39.
Getting Started
I've used CDN for Bootstrap and Angular JS in this tutorial so you need internet connection for them to work.Creating our Database
First, we're gonna create our 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.index.html
This is our index that contains our add form, table and select input.- <!DOCTYPE html>
- <html lang="en" ng-app="app">
- <head>
- <meta charset="utf-8">
- <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
- <style type="text/css">
- .errortext{
- color:red;
- }
- </style>
- </head>
- <body ng-controller="myController" ng-init="fetch()">
- <div class="container">
- <div class="col-md-2 col-md-offset-1">
- </div>
- <div class="col-md-6">
- <table class="table table-bordered table-striped">
- <thead>
- <tr>
- <tr>
- </thead>
- <tbody>
- <tr ng-repeat="fruit in fruits">
- </tr>
- </tbody>
- </table>
- </div>
- <div class="col-md-2">
- <!-- <select ng-model="selectedFruit">
- <option ng-repeat="x in fruits" value="{{x.fruitid}}">{{x.fruitname}}</option>
- </select> -->
- <select ng-model="selectedFruit" ng-options="x.fruitname for x in fruits" class="form-control">
- </select>
- <hr>
- <!-- <p><b>You selected:</b> {{selectedFruit}}</p> -->
- </div>
- </div>
- </body>
- </html>
angular.js
This contains our angular js scripts.- var app = angular.module('app', []);
- app.controller('myController', function($scope, $http){
- $scope.fetch = function(){
- $http.get("fetch.php").success(function(data){
- $scope.fruits = data;
- });
- }
- $scope.add = function(){
- //console.log($scope.newFruit);
- $http.post("add.php", $scope.newFruit)
- .success(function(){
- $scope.newFruit = '';
- $scope.fetch();
- });
- }
- });
fetch.php
This is our PHP code/api that fetches data from our database.- <?php
- $conn = new mysqli('localhost', 'root', '', 'angular');
- $sql = "SELECT * FROM fruits";
- $query=$conn->query($sql);
- while($row=$query->fetch_array()){
- $output[] = $row;
- }
- ?>
add.php
This is our PHP code/api in adding data into our table.- <?php
- $conn = new mysqli('localhost', 'root', '', 'angular');
- $fruitname = $data->fruitname;
- $sql = "INSERT INTO fruits (fruitname) VALUES ('$fruitname')";
- $conn->query($sql);
- ?>