With only using AngularJS it is not possible to get data from the MySQL database because it only handles Client-side requests.
You have to use any Server side language at the backend which handles the request and returns the response.
In AngularJS $http
service is used to send AJAX requests.
Contents
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 for database configuration.
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
Array.
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 a getData.php
file.
From here return JSON Array which has user details (fname, lname, and username).
Completed Code
<?php 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
inurl
and setmethod
toget
. - Success – AJAX successfully callback handle by
then
where storereponse.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. Demo
7. 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 the tutorial example, I send a GET request from $http
to fetch data from the MySQL database in JSON format.
Nice blog to get started on angular with server side language.
this does not work.
nevermind.. it was just a chmod problem
Hi Jesse,
I have rechecked the code its working and attached the working demo on the tutorial.
sir it is not working
it only show the table heading
bt not shown the data
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.
same problem occuring at mt side
Great! Its working!
Glad it was helpful.
Great tutorial thank, simple yet very useful
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?
wow. it’s working
Thank you . How to insert database
Hi Vijay,
View this tutorial for data insertion.
its work , thanks
You’re welcome.
this does not work.
Hi Rakesh,
Is any error display in the Browser console.
It helps me a lot! Thank you so much!
You’re welcome.
Any Thoughts to resolve this: ? I am trying to do the same process with a MySql table I created bbTmsDefm with mTmsFN (fullname), mTmsAbrv, mTmsConf, mTmsDiv, and mTmsInitRank.
I am thinking the ng-repeat line is wrong in my script where does the “user in users” come from?
angular.js:13562 Access to XMLHttpRequest at ‘file:///C:/Users/TMatthews/Downloads/0%20-%20Angular%20PHP%20MySql%20examples/getData.php’ from origin ‘null’ has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
(anonymous) @ angular.js:13562
angular.js:15567 Possibly unhandled rejection: {“data”:null,”status”:-1,”config”:{“method”:”GET”,”transformRequest”:[null],”transformResponse”:[null],”jsonpCallbackParam”:”callback”,”url”:”getData.php”,”headers”:{“Accept”:”application/json, text/plain, */*”}},”statusText”:””,”xhrStatus”:”error”}
Hi Tom,
Have you not stored getData.php file in htdocs/ directory?
I tried replying this morning early but got an error message so I’ll try again & individually.
Yes, I have the getData.php stored & saved:
$row[‘mTmsFN’],”mTmsAbrv”=>$row[‘mTmsAbrv’],”mTmsConf”=>$row[‘mTmsConf’],
“mTmsDiv”=>$row[‘mTmsDiv’],”mTmsInitRank”=>$row[‘mTmsInitRank’]);
}
echo json_encode($data);
?>
My config.php is:
And the ht,l is:
How to get data from MySQL with AngularJS – PHP
TeamFN
TeamAbrv
TeamConf
TeamDiv
TeamInitRank
{{bbTmsDefm.mTmsFN}}
{{bbTmsDefm.mTmsAbrv}}
{{bbTmsDefm.mTmsConf}}
{{bbTmsDefm.mTmsDiv}}
{{bbTmsDefm.mTmsInitRank}}
var fetch = angular.module(‘myApp’, []);
fetch.controller(‘dbCtrl’, [‘$scope’, ‘$http’, function ($scope, team, $http) {
$http({
method: ‘get’,
url: ‘getData.php’
}).then(function successCallback(response) {
$scope.team = response.data;
});
}]);
Let me try this again. I cannot connect to my MySql database, all it says is $http is not a function. Here are the files individually.
index.http:
How to get data from MySQL with AngularJS – PHP
http://angular.js
TeamFN
TeamAbrv
TeamConf
TeamDiv
TeamInitRank
{{bbTmsDefm.mTmsFN}}
{{bbTmsDefm.mTmsAbrv}}
{{bbTmsDefm.mTmsConf}}
{{bbTmsDefm.mTmsDiv}}
{{bbTmsDefm.mTmsInitRank}}
“use strict”;
var fetch = angular.module(‘myApp’, []);
fetch.controller(‘dbCtrl’, [‘$scope’, ‘$http’, function ($scope, teams, $http) {
$http({
method: ‘get’,
url: ‘getData.php’
}).then(function successCallback(response) {
$scope.team = response.data;
});
}]);
How to get data from MySQL with AngularJS – PHP
http://angular.js
TeamFN
TeamAbrv
TeamConf
TeamDiv
TeamInitRank
{{bbTmsDefm.mTmsFN}}
{{bbTmsDefm.mTmsAbrv}}
{{bbTmsDefm.mTmsConf}}
{{bbTmsDefm.mTmsDiv}}
{{bbTmsDefm.mTmsInitRank}}
“use strict”;
var fetch = angular.module(‘myApp’, []);
fetch.controller(‘dbCtrl’, [‘$scope’, ‘$http’, function ($scope, teams, $http) {
$http({
method: ‘get’,
url: ‘getData.php’
}).then(function successCallback(response) {
$scope.team = response.data;
});
}]);
This site is useless, it’s stripping out a lot of code.
Very nice tutorial. Do you have tutorial on how to Add, Update, Delete and show data in SPA using Angular HTML, and PHP?
I am getting this error. Any idea on how to fix this ?
Here is the error in console :
DevTools failed to load SourceMap: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/include.postload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME
Hi–
All I get is this error in the console. No data is being displayed:
angular.min.js:122 Error: [ngRepeat:dupes]
Is there to way to put the php code in the same file?? because in this case it echoes data to the page not sending as respose to the AngularJS code
Hi Abdul,
Yes, you can do that. View the following tutorial for reference.
It’s working ….Thank you so much makitweb..:)
You’re welcome.
pls…post ..this same concept with using two or more tables using join query’s on fetching data’s..pls post through angular js and php