How to get data from MySQL with AngularJS – PHP

With only using AngularJS it is not possible to get data from MySQL database because it only handles Client side requests.

You have to use any Server side language at backend which handles the request and returns response.

In AngularJS $http service is use to send AJAX request.

How to get data from MySQL with AngularJS - PHP


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. Script
  6. Conclusion

 


 

1. Table structure

I am using users table in the tutorial example.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `fname` varchar(80) NOT NULL,
  `lname` varchar(80) NOT NULL,
  `username` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

2. Configuration

Create a new config.php file.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

 

3. HTML

You can either download and include angular.min.js in the page or use CDN.

<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js'></script>

Define <body ng-app='myapp'> and <div ng-controller='userCtrl'> on the page.

For displaying data create a <table> layout and specify ng-repeat directive on a row. Which loop through all available data in users property.

Completed Code

<!doctype html>
<html>
 <head>
  <title>How to get data from MySQL with AngularJS - PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
 
 </head>
 <body ng-app='myapp'>

  <div ng-controller="userCtrl">
 
  <table >
 
  <tr>
  <th>First name</th>
  <th>Last name</th>
  <th>Username</th>
  </tr>
  
  <!-- Display records -->
  <tr ng-repeat="user in users">
  <td>{{user.fname}}</td>
  <td>{{user.lname}}</td>
  <td>{{user.username}}</td>
  </tr>
 
  </table>
  </div>
 
 </body>
</html>

 


 

4. PHP

Create new getData.php file.

From here return JSON Array which has user details (fname, lname, and username).

Completed Code

include 'config.php';

$sel = mysqli_query($con,"select * from users");
$data = array();

while ($row = mysqli_fetch_array($sel)) {
 $data[] = array("fname"=>$row['fname'],"lname"=>$row['lname'],"username"=>$row['username']);
}
echo json_encode($data);

 

5. Script

Create new module and setup AJAX request in controller ( userCtrl ).

  • Path – Passing file name getData.php in url and set method to get.
  • Success – AJAX successfully callback handle by then where store reponse.data to $scope.users.

At HTML end display data using ng-repeat directive.

Completed Code

<script>
var fetch = angular.module('myapp', []);

fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
 $http({
  method: 'get',
  url: 'getData.php'
 }).then(function successCallback(response) {
  // Store response data
  $scope.users = response.data;
 });
}]);

</script>

 

6. Conclusion

Angular provide $http service which helps to make an AJAX call to the server.

Similar to jQuery AJAX request you can either send GET or POST type request. Within tutorial example, I send GET request from $http to fetch data from MySQL database in JSON format.

Related Post

Spread the love
  • 3
  •  
  •  
  •  
  •  
  •  

12 Comments

  1. Vishal said:

    Nice blog to get started on angular with server side language.

    February 15, 2017
    Reply
  2. jesse said:

    this does not work.

    September 21, 2017
    Reply
    • jesse said:

      nevermind.. it was just a chmod problem

      September 21, 2017
      Reply
    • Yogesh Singh said:

      Hi Jesse,
      I have rechecked the code its working and attached the working demo on the tutorial.

      September 21, 2017
      Reply
  3. shyam said:

    sir it is not working
    it only show the table heading
    bt not shown the data

    January 17, 2018
    Reply
    • Yogesh Singh said:

      Hi Shyam,
      I think there is an error in your script because of that data is not loading. Check the browser console to find the error.

      January 17, 2018
      Reply
  4. Pushkar said:

    Great! Its working!

    March 28, 2018
    Reply
  5. Arbando said:

    Great tutorial thank, simple yet very useful

    April 21, 2018
    Reply
  6. Charles said:

    XML Parsing Error: unclosed token
    Location: file:///C:/xampp/htdocs/Assignment6/getData.php
    Line Number 1, Column 1:

    <?php

    The error is referring to "<?php".

    I don't know what to do. Any suggestions?

    April 29, 2018
    Reply
  7. Vijay said:

    wow. it’s working
    Thank you . How to insert database

    October 1, 2018
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *