Call database data with $ http get

0

I'm not able to call the database 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();
};
    
asked by anonymous 19.03.2017 / 11:41

2 answers

3

First your variable definition is incorrect, try the following:

var showCat = function() {...

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

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

So you already send the data in JSON .

    
19.03.2017 / 12:53
1

The way that you are using the json_encode function is strange.

You do not need to create a string formatted in json , you can directly pass the array results to it:

(I'm assuming that this PHP file is just a snippet of code, if it's the whole file it will always return "Could not connect to 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();
};
    
19.03.2017 / 12:54