I'm new to web development and so this might be a simple issue for some and hopefully a useful thread for other beginners.
I'm selecting some data (accounts) from a mysql database by using a php script. I want this selected data to be passed to an angular variable so I can create the output by using ngRepeat. What do I have to change in my PHP and/or Angular files?
Now that the JSON is build the problem is, that I don't get back to the html I called the PHP from. How do I manage that?
Thank you for your help Chris
HTML
<form action="./backend/display_accounts.php" method="post">
<input class="btn btn-default" type="submit" value="display accounts"/>
</form>
<ul>
<li ng-repeat="account in accounts">
{{ account.account_name }}
</li>
</ul>
PHP
<?php
include 'connect.php';
$sql = //myQuery//
$result = $conn->query($sql);
//return ($result);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$json_arry = json_encode($row);
echo $json_array;}
}
else {
echo "0 results";
}
$conn->close();
?>
AngularJS
var app = angular.module("myApp", ['ngRoute'])
app.controller('accountsController', function($scope, $http) {
$scope.displayData = function(){
$http.get("./backend/display_accounts.php")
.then(function (response) {$scope.accounts = response.data.records;});
};
});
Since you have already obtained the data into a variable (accounts). You can use following code in the html to see the results
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp">
<p>Looping with ng-repeat:</p>
<ul>
<li ng-repeat="account in accounts">
{{ account }}
</li>
</ul>
</div>
</body>
</html>
I think you should change a bit . In php
$sql = //myQuery//
$row = array(); //here is change
$result = $conn->query($sql);
return ($result);
if ($result->num_rows > 0) {
while($r= $result->fetch_assoc()) {
$row[]= $r; //here is change
$json_arry = json_encode($row);
echo $json_array;
}
And in angular
$http.get("./backend/display_accounts.php")
.then(function (response) {$scope.accounts = response.data;}); //you dont need record in here if json file of you dont have the key records
};
if json file of you like you should need records but if not . you dont need it.
{"records":
[
{// your data}]}
If json file of you have a ,b ,c or some thing instead records , you should write like this
$scope.accounts = response.data.a; //a b c or some thing for ex I use a
And you can display in html like
<ul ng-repeat= account in accounts>
<account. ...>
</ul>