Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Display data from MySQL using PHP and angular JS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 885
    Comment on it

    Hello friends,

    Today we will learn how to fetch data from MySQL and display it using angular JS. First we will make a PHP  file for retrieving data.

    dbresult.php

    <?php
    
            // set up the connection variables
            $dbname  = 'dbname';
            $hostname = 'hostname';
            $username = 'mysql_username';
            $password = 'mysql_password';
    
            // connect to the database
            $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
    
            // a query get all the records from the users table
            $sql = 'SELECT id, name FROM tablename';
    
            // use prepared statements, even if not strictly required is good practice
            $stmt = $dbh->prepare( $sql );
    
            // execute the query
            $stmt->execute();
    
            // fetch the results into an array
            $result = $stmt->fetchAll( PDO::FETCH_ASSOC );
    
            // convert to json
            $json = json_encode( $result );
    
            // echo the json string
            echo $json;
    ?>

    In above file we have done connectivity using PDO.

    Now, we will create a file where we fetch the data using angular js from file dbresult.php and display the data.

    display_result.php

    <!DOCTYPE html>
    <html>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>
    
    <div ng-app="myApp" ng-controller="customersCtrl">
    
    <table>
      <tr ng-repeat="x in names">
        <td>{{ x.id }}</td>
        <td>{{ x.name }}</td>
      </tr>
    </table>
    
    </div>
    </body>
    </html>
    
    <script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http) {
        $http.post("dbresult.php")
        .then(function (response) {$scope.names = response.data;});
    });
    </script>

    In above code we will call dbresult.php file and display the response coming from this file.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: