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'}]