Fetching data from local mysql using angular not working

1.2k Views Asked by At

I been trying to fetch data from MySql from the local server. My local server is WAMP.

Here my index.php

<html lang="en-US">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app='myApp'>
<div ng-controller="customersCtrl">
    <table>
    <thead><tr><th>ID</th><th>Name</th><th>Email</th></tr></thead>
    <tbody>
        <tr ng-repeat="user in names">
            <td>{{user.id}}</td>
            <td>{{user.name }}</td>
            <td>{{user.city}}</td>
        </tr>
    </tbody>
    </table>
</div>  
<script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http) {
        $http.get("customers_mysql.php")
        .success(function (response) {$scope.names = response.records;});
    });
</script>
</body>
</html>

Here is my customers_mysql.php

$conn = new mysqli("localhost", "root", "", "test");
$sql = "SELECT name, city, country FROM customers";
$results = mysqli_query($conn, $sql);
$data = array();

while($row = mysqli_fetch_assoc($results)) {
    $data[] = $row;
}

$json = json_encode( $result );
echo $json;

When i load index.html page i get no results at all. So i thought it mite be something wrong with my sql so i created a new php page

called textCustomers.php

<?php
    include('customers_mysql.php');
    $results = mysqli_query($conn, $sql);


    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } else {
        if (mysqli_num_rows($results) > 0) {
            while($row = mysqli_fetch_assoc($results)) {
                echo '<tr>';
                echo '<td>' . $row['name'] . '</td>';
                echo '</tr>';
            }
        }
    }

?>

This works.

Anyway i been following code from stackoverflow, w3 and other site but none of them work. What i am doing wrong?

Thank you

1

There are 1 best solutions below

0
On

Try something like this:

$conn = new mysqli("localhost", "root", "", "test");
$sql = "SELECT id, name, city FROM customers";
$results = mysqli_query($conn, $sql);
$data = array();

while($row = mysqli_fetch_assoc($results)) {
    $data[] = $row;
}

$json = json_encode( $data );
echo $json;