Calling database data with $http get

Asked

Viewed 146 times

0

I am not able to call the database data with the method below:

<div class="container" ng-app="appCat">
    <div class="row" ng-controller="appCatCtrl">
        <table class="table table-striped">
            <tr>
                <th>Nome</th>
                <th>Telefone</th>
            </tr>
            <tr ng-repeat="x in category">
                <td>{{x.cat}}</td>
                <td>{{x.sub}}</td>
            </tr>
        </table>
    </div>
</div>

In the JS file:

angular.module("appCat", []);
angular.module("appCat").controller("appCatCtrl", function ($scope, $http) {
    $scope.category = [];
    var showCat() {
        $http.get("proc_cat.php").then(function(response) {
            $scope.category = response.data;
        });
    }
    showCat();
});

and in PHP:

try {
    $con = new PDO($dns, $user, $pass);
    if(!$con){
        echo "Não foi possivel conectar com Banco de Dados!";
    }
    $query = $con->prepare('SELECT * FROM category');
        $query->execute();
        $out = "[";
        while($result = $query->fetch()){
            if ($out != "[") {
                $out .= ",";
            }
            $out .= '{"cat": "'.$result["name_cat"].'",';
            $out .= '"sub": "'.$result["sub_cat"].'"}';
        }
        $out .= "]";
        echo utf8_encode($out);
} catch (Exception $e) {
    echo "Erro: ". $e->getMessage();
};

2 answers

3


First your variable definition is incorrect, try it this way:

var showCat = function() {...

Another thing would be your data processing on the PHP side. You are doing something very complex to generate the array, and you could just use the functions json_encode() (to send from PHP to Angular - JS) and json_decode() (to upload from Angular - JS to PHP).

$query->execute();
$resposta = $query->fetchAll();
return json_encode($resposta);

So you also send the data in JSON.

1

The way you are using the function json_encode is strange.

You don’t need to create a string formatted in json, can directly pass the array of results for him:

(I am assuming that this PHP file is just a snippet of code, if it is the entire file it will always return "It was not possible to connect with Database!")

try {
    $con = new PDO($dns, $user, $pass);
    if(!$con){
        echo "Não foi possivel conectar com Banco de Dados!";
    }
    $query = $con->prepare('SELECT * FROM category');
        $query->execute();

        $out = [];

        while($result = $query->fetch()){
            $out[] = [
                'cat' => $result["name_cat"],
                'sub' => $result["sub_cat"],
            ];
        }

        echo utf8_encode($out);

} catch (Exception $e) {
    echo "Erro: ". $e->getMessage();
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.