AngularJS Get JSON Data From MYSQL Database Using PHP PDO

In this post we will see for Front End AngularJS how to get JSON data from MYSQL Database using PHP and PDO(PHP Data Objects).

AngularJS is popular JavaScript framework, used for front-end development. If you want fetch data from database you have to use any server side language like PHPnode.js, ASP.NET etc. You cannot show data directly from database to front end side. I will explain with simple example in step by step method. But, you should have a basic knowledge of HTML, Javascript and PHP-PDO.

 

1. HTML Code

index.html :

In above source code, on line 4. you can either use direct CDN path for including angular.min.js or you can Download.

1. On Line 6 : ng-app is a directive that defines AngularJS application. ng-controller directive defines the controller.
2. Line 11 : ng-repeat is directive repeats an HTML element, used on an array of objects.
3. Line 12 : AngularJS expressions are always written inside double braces: {{ write expression here }}.
4. At the end, on Line 17 fetch.js included which is actual AngularJS code.

 

2. AngularJS Code

fetch.js :

In above code AngularJS code included:

1. Line 1 : AngularJS module defined which is a container for the application controllers. A module is created by using the AngularJS function angular.module. The “myFetch” parameter refers to an HTML element.
2. Line 2 : Controller added. Here you can refer ng-controller directive. AngularJS controllers control the data which are regular JavaScript Objects. Here $scope is a object which binds the HTML (view) and the JavaScript (controller).
3. On Line 3 : $http is AngularJS service which makes a request to the server, and returns a response. Here I have used get() method. Note that $http is an XMLHttpRequest object.
4. Line 4: The JSON response data received from remote server. The response data wrapped in array called players.

3. PHP Code

fetch.php :

In above code, I have made MYSQL database connection using PHP PDO which fetch the data from database and send response in JSON format to front-end AngularJS.

1. On Line 8 : $conn object is created and made connection between PHP file and MYSQL database by using PHP- PDO. You can refer Here for more information about PDO.
2. Line 18 : ‘name‘ and ‘country‘ of each row inserted in array called ‘players‘.
3. On Line 21 : The array data encoded in JSON format and sent to front-end AngularJS.

 

4. Result

You can see the following image which shows actual output of response of server on front-end side using AngularJS

AngularJS Get JSON Data From MYSQL Database Using PHP PDO
AngularJS Get JSON Data From MYSQL Database Using PHP PDO

In this way for AngularJS you fetch or get JSON data from MYSQL Database using PHP and PDO(PHP Data Objects). You can comment below, if you have any questions and doubt.

3 comments

Leave a Reply