How to display php / mysql and AngularJs data?

3

I'm trying to do a test with PHP + MySQL + AngularJS and I was left with a question about how to handle the bank data with angular and send to screen, I have the following codes:

con-bd.php

<?php
....

$conn = mysqli_connect($host, $user, $pass, $base) or die(mysqli_error());

$query = "SELECT matricula, nome FROM sca_pessoa" or die(mysqli_error());

$result = $conn->query($query);

while ($row = mysqli_fetch_array($result)) {
    $json_str = json_encode($row)   
    echo $json_str;
}

# retorna json assim, meio errado?
/*
{"0":"182354X","matricula":"182354X","1":"RAFAEL CAMPOS PIMENTEL","nome":"RAFAEL CAMPOS PIMENTEL"}
{"0":"1823558","matricula":"1823558","1":"RAQUEL CARVALHO SANTANA","nome":"RAQUEL CARVALHO SANTANA"}
{"0":"182371X","matricula":"182371X","1":"JULIANA PINHEIRO GOMES","nome":"JULIANA PINHEIRO GOMES"}
*/

app.js

var app = angular.module("app", []);

app.controller("pessoasCtrl", function($scope) {

}); 

Index.php

<!DOCTYPE html>
<html ng-app="app">
<head>
    <meta charset="utf-8">
    <title>App com PHP e AngularJS</title>
    <link rel="stylesheet" href="css/bootstrap.css">
    <script src="js/angular.js"></script>
    <script src="js/app.js"></script>
</head>
<body>

    <div ng-controller="pessoasCtrl">
        <h3>App PHP + AngularJS</h3>

    </div>
</body>
</html>

So, I'm kind of trying to figure out how I'm going to do this exactly.

    
asked by anonymous 14.04.2015 / 14:13

6 answers

3

JSON Format
It seems to me that you are wanting to pass a collection, but it is returning 3 objects. The ideal format would look like this:

[
{"0":"182354X","matricula":"182354X","1":"RAFAEL CAMPOS PIMENTEL","nome":"RAFAEL CAMPOS PIMENTEL"},
{"0":"1823558","matricula":"1823558","1":"RAQUEL CARVALHO SANTANA","nome":"RAQUEL CARVALHO SANTANA"},
{"0":"182371X","matricula":"182371X","1":"JULIANA PINHEIRO GOMES","nome":"JULIANA PINHEIRO GOMES"}
]

Note the brackets (which determine the beginning and end of a collection) and commas (separating objects individually).

Interpreting JSON

You can use the $http service to load and interpret content from the database:

$http.get('con-bd.php').success(function(response) {
    return response.data;
});
    
14.04.2015 / 16:55
3

This is due to the array that is returned from the MySQL function mysqli_fetch_array . In this array, it maps the value of the column by index and column name, so you see the same value mapped to both 0 and matricula .

Ideally, you map this output to another array as you wish. For example:

$response = array();

 while ($row = mysqli_fetch_array($result)) {
     $json["matricula"] = $row[0];
     $json["nome"] = $row[1];
     array_push($response, $json);  
}

echo json_encode($response);

The interesting thing is to map this to a Aluno class and transform that class into JSON.

    
15.04.2015 / 18:41
2

I went through a similar situation these days, in my case I threw the result to another array to then code for json. In the following example is a snippet of my code that I used, in this case my connection is PDO and I am returning as Object, to advance things, analysis the example I believe may help you:

$smtt_select = $conn->prepare('SELECT * FROM contatos');
$smtt_select->execute();

$res = [];

while($resultado = $smtt_select->fetch(PDO::FETCH_OBJ)){
    array_push($res, $resultado);
}

$json = json_encode($res);

echo $json;
    
16.04.2015 / 00:42
1

app.js // create the server

var app = angular.module('myApp', ['ngRoute']);
app.factory("services", ['$http', function($http) {
  var serviceBase = 'services/'
    var obj = {};
    //busca os dados do cliente
    obj.getPessoas = function(){
        return $http.get(serviceBase + 'pessoas');
    }
    return obj;   
}]);
//cria a controller
app.controller('lista', function ($scope, services) {
    services.getPessoas().then(function(data){
        $scope.pessoas = data.data;
    });
});
//Cria as rotas
app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        title: 'Exemplo Angular php',
        templateUrl: 'partials/exemplo.html',
        controller: 'lista'
      })
      .otherwise({
        redirectTo: '/'
      });
}]);
//roda a app
app.run(['$location', '$rootScope', function($location, $rootScope) {
    $rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
        $rootScope.title = current.$$route.title;
    });
}]);

Better than that!

    
16.04.2015 / 17:14
1

I know you already have several answers here, but I would like to solundate your problem based only on the data you gave. First, let's start where you started, in con-bd.php :

<?php
...

$conn = mysqli_connect($host, $user, $pass, $base) or die(mysqli_error());

$query = "SELECT matricula, nome FROM sca_pessoa" or die(mysqli_error());

$result = $conn->query($query);

//Declare uma array para colecionar todos os $rows
$end_result = array();

/*
   Aqui, em vez de usar mysqli_fetch_array(), que devolve ambos
    arrays associativas e arrays numericais, usa mysqli_fetch_assoc -
    assim, consegue pegar uma array associativa assim:
    ['matricula'=>'182354X', 'nome'=>'RAFAEL CAMPOS PIMENTEL']
*/
while ($row = mysqli_fetch_assoc($result)) {
    //adicione essa array associativa à array normal
    $end_result[] = $row;
}

//specifique-se que o conteúdo é do JSON - AngularJS vai gostar disso :D
header('Content-Type: application/json');

//Por fim, transforme o array em JSON e termina a execução.
echo json_encode($end_result);
die();
?>

Then, on your app.js , you need to define the service that makes this call to con-bd.php . A simple example () based on a other answer to that question ) :

var app = angular.module("app", []);

app.factory('services', ['$http', function($http) {
    var obj={};
    obj.getPessoas = function() { return $http.get('con-bd.php'); }
    return obj;
}]);

app.controller("pessoasCtrl", function($scope, services) {
    services.getPessoas().then( function(data) {
        $scope.pessoas = data.data;
    } );
});

app.run();

And finally, in your Index.html , you would need something like this (well popped up with the original, simply adding the bindings):

<!DOCTYPE html>
<html ng-app="app">
<head>
    <meta charset="utf-8">
    <title>App com PHP e AngularJS</title>
    <link rel="stylesheet" href="css/bootstrap.css">
    <script src="js/angular.js"></script>
    <script src="js/app.js"></script>
</head>
<body>

    <div ng-controller="pessoasCtrl">
        <h3>App PHP + AngularJS</h3>
        <div ng-repeat="pessoa in pessoas">
            <b>Matricula:</b> {{pessoa.matricula}} <br/>
            <b>Nome:</b> {{pessoa.nome}}
        </div>
    </div>
</body>
</html>

Using these exact codes, I was able to put the appropriate data on the site. Of course I was without any CSS, but I was able to show things. The biggest detail is the way I was reading the database. If you do not specify MYSQLI_ASSOC when you use mysqli_fetch_array() , it will return both associative and numeral - which translates directly to the strange JSON you were seeing.

Another detail is that you have to remember that an array in PHP does not always translate to an array in JSON - the rule is as follows:

PHP                  JSON
-----------------    -------
array associativa    objeto
array numeral        array

That is:

['nome'=>'joao']       --> {nome:'joao'}
[0=>'nome']            --> ['nome']
[0=>['nome'=>'joao']]  --> [{nome:'joao'}]
    
30.07.2015 / 07:57
0

Try this:

$result = array();
while($row = $r->fetch_assoc()){
    $result[] = $row;
}
json_encode($data);

This should solve your problem, have to see the call of your server tbm:

return $http.get(serviceBase + 'customers');
    
16.04.2015 / 17:08