1

I want to display data which I select from a mySQL database using PHP. The data should be shown in angular variables. I can see the JSON when clicking a button I installed. But the data will not show up in the angular variables. So I think the problem is the communication between php and angular on the way back from php to angular.

Here are the files I use. Where do i have to make changes to get what I want?

Thank you!

index.html

<!DOCTYPE html>
<html ng-app="MyApp">
  <head>
    <title>nutrimeal</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/main.css">
  </head>
  <body>
    <div class="container-fluid">
      <div class="col-sm-10 content">
        <h1>M E A L S</h1>
        <form action="./php/meal_select.php" method="post">
          <input class="btn btn-default" type="submit" value="display meals"/>
        </form>
        <div ng-controller = "MealsController as meals">
          <p>The meals should be shown underneath</p>
          <div ng-repeat="meal in meals">
            {{ meal.name }}
            {{ meal.daytime }}
          </div>
        </div>
      </div>
    </div>
<!-- Javascript references -->
    <script src="./js/vendors/bootstrap.js"></script>
    <script src="./js/vendors/angular.js"></script>
    <script src="./js/app.js"></script>
  </body>
</html>

app.js

var app = angular.module('MyApp', ['ngRoute'])

// MealsController
app.controller('MealsController', [ '$http', function($scope, $http) {
  $scope.displayData = function(){
    var meals =  $http.get('./backend/meal_select.php')
//   .then(function (response) {$scope.accounts = response.data.records;} );
    .then(function (data) {
      $scope.meals = data });
};
$scope.displayData()
}]);

meal_select.php

<?php

// connection settings
$servername = "localhost";
$username = "root";
$password = "qwertz";
$dbname = "example_nutrition";

// create connection to db
$conn = new mysqli($servername, $username, $password, $dbname);

// check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// set SQL command
$sql = "SELECT meal_id, name, daytime FROM meal";

// query db
$result = $conn->query($sql);

// show results
if ($result->num_rows > 0) {
    // output data of each row
    $r=array()
    while($row = $result->fetch_assoc()) {
       $r=[] = $row;
//simple output
    // echo " Account Name: " . $row["account_name"].
      //    " Balance: " . $row["initial_balance"].
        //  " Currency: " . $row["currency"].  "<br>";

// output as JSON
     //$json_array = json_encode($row);
     $json_array = json_encode($r);
     header('Content-type: application/json');
     echo $json_array;
  }
}
// if nothing was found
          else {
            echo "0 results";
}

// close connection to db
$conn->close();
?>

JSON displayed after clicking the button

{"meal_id":"1","name":"cheeseburger","daytime":"lunch"} {"meal_id":"2","name":"chili con carne","daytime":"lunch"}

16
  • your json file are object ? Commented May 5, 2017 at 11:29
  • What does that mean? Where can I look that up? Commented May 5, 2017 at 14:33
  • In app.js I changed "$scope.accounts to "$scope.meals" and "var accounts" to "var meals" Commented May 5, 2017 at 14:35
  • following my code in edit Commented May 5, 2017 at 14:36
  • you dont need use var Commented May 5, 2017 at 14:37

1 Answer 1

0

EDIT

PHP

$row = array();
$sql = "SELECT * FROM ...";
$result = mysqli_query($conn,$sql);
if($result){
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}
print json_encode($rows);

Angular

  $scope.showData = function(){
    $http.get('data.php').then(function(response){
                $scope.data = response.data;
   }
   $scope.showData();

});

HTML

<ul ng-repeat ="d in data">
<li> {{d.name}}</li>
<li> {{d.age}}</li>
 ...
</ul>

I think this code above is simple and you can understand , but I will explain a bit. In angular we have two options for ng-repeat:

1.Object

2.Array

If you are using an object inside ng-repeat then you need to use it something like this:

<ul ng-repeat="(key, value) in data">  
   <li> {{ key }} : {{ value }}</li>  
</ul>

And if you are using array inside ng-repeat then you can do like this:

<ul ng-repeat="d in data">  
    <li>{{ d.name}}</li> 
    <li>{{ d.age}}</li> 
</ul>

Now understand what is happening here, you are getting a response from server which is an object and trying to print it like an array and it reason why it not work (and you forget invoked function). This is why I talk you add two line code in php

$row = array();
$rows[] = $r;

If you dont have two line , your json is object and you cant print it like array . But if you have two line , your json is array and you can print it like array

Sign up to request clarification or add additional context in comments.

3 Comments

I copied files from the tutorial which you can find under the following link. And there is the same problem - no data will be shown. I thought about a browser problem, but chrome and safari had the same problem. Do you have any idea? webslesson.info/2016/09/…
This tutorial is out of date . In show data you should change to .then(function(data){ $scope.names = data.data; . And can you post full your json file
@Krs81 you can following this code in this post stackoverflow.com/questions/43820731/… . It delete but same with insert . You just change code in php , insert directly instead use switch case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.