How to view php/mysql and Angularjs data?

Asked

Viewed 12,215 times

3

I’m trying to do some tests with PHP + Mysql + Angularjs and I was stuck in a doubt of how to treat the database 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 exactly I’m gonna do this.

6 answers

3

JSON format
It seems to me that you are wanting to pass a collection but are returning 3 objects. The ideal format would be 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"}
]

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

Interpreting JSON

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

$http.get('con-bd.php').success(function(response) {
    return response.data;
});
  • I understand, but the point is that this json is coming out wrong. =\

  • @phpricardo It would be the case then that you adjust con-db.php to include square brackets (at the beginning and end) and commas (for all lines except the last).

  • But why is this json that comes out the way it comes out, double the number and name? That’s what I’m finding strange. I saw some code that can create a format even, but I think I could have it already ready (php function).

3

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

Ideally you map this result 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 would be to map this to a class Aluno and turn this class into JSON.

  • Paul gave more or less certain, but the point is that it still doubles and he still creates [{ ... }] for each data.

  • I updated the answer. See if it works like this.

2

I went through a similar situation these days, in my case I played the result for another array to later encode for json. In the following example is an excerpt of my code that I used, in this case my connection is PDO and I am returning as Object, already to advance things, analysis the example I believe can 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;
  • I adapted my code to Pdo tb and did as you did, but no results =( dirty this. Only mine that doesn’t work. http://pastebin.com/ucjmXzJ3

  • In your code you are using while($Row = $smt_select->fetch() try using "fetch(PDO::FETCH_OBJ)" as I did.

1

I know you already have several answers here, but I’d like to remedy your problem based solely on the data you had given. First, let’s start where you started, at 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 his app.js, needs to define the service that makes this call to con-bd.php. A simple example (based on a another answer to that same 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 at the end, in his Index.html, would need something like this (nicely appeared 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 exactly these 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 you were reading the database. If you do not specify MYSQLI_ASSOC when you use mysqli_fetch_array(), will return both associative and numeral - which translates directly to the strange JSON you were seeing.

Another detail, too, 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 to say:

['nome'=>'joao']       --> {nome:'joao'}
[0=>'nome']            --> ['nome']
[0=>['nome'=>'joao']]  --> [{nome:'joao'}]

1

app js. //creates 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 impossible!

0

Try it this way:

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

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

return $http.get(serviceBase + 'customers');

Browser other questions tagged

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