1

I'm learning AngularJS and wondered how I could get the PHP database results into an angular model. What I have:

<!DOCTYPE html>
<html data-ng-app="statsApp">
  <head>
    <title>Student Stats</title>
    <script src="angular.min.js"></script>
    <link href="bootstrap.css" rel="stylesheet" />
    <link href="bootstrap-theme.css" rel="stylesheet" />

<?PHP
  // Include dbcreds.inc for db info.
  include('dbcreds.inc');

  if(isset($_GET['fname']) && $_GET['fname'] !== "")
  {
    $lname = $_GET['fname'] . "%";

    $sql = $conn->prepare("select * from students where fname like ?");

    $sql->execute(array($lname));

    $res = $sql->fetchAll();

    $rownum = 0;

    echo "\n    <SCRIPT>";
    echo "\n      var model = [";
    foreach($res as $r)
    {
      $rownum++;
      echo "\n        ";
      print_r(json_encode(array("ID" => intval($r['id']),"FNAME" => $r['fname'],"LNAME" => $r['lname'],"GPA" => doubleval($r['gpa']))));

      // Add a comma, if it's not the last datarow.
      if($rownum < count($res))
      {
        echo ",";
      }
    }

    echo "\n      ];";
    echo "\n      ";
    echo "\n      var statsApp = angular.module(\"statsApp\",[]);";
    echo "\n      ";
    echo "\n      statsApp.controller(\"statsAppCtrl\", function (\$scope) {";
    echo "\n        \$scope.stats = model;";
    echo "\n      });";

    echo "\n    </SCRIPT>\n  ";
  }
?>
  </head>
  <body data-ng-controller="statsAppCtrl">
    <div class="page-header">
      <h2>
        <span class="label label-default">{{ stats.length }}</SPAN>
      </h2>
    </div>
    <div class="panel">
      <table class="table table-striped">
        <thead>
          <TR>
            <TH>ID</TH>
            <TH>First Name</TH>
            <TH>Last Name</TH>
            <TH>GPA</TH>
          </TR>
        </thead>
        <tbody>
          <tr data-ng-repeat="stats_item in stats | orderBy:'ID'">
            <td>{{ stats_item.ID }}</td>
            <td>{{ stats_item.FNAME }}</td>
            <td>{{ stats_item.LNAME }}</td>
            <td>{{ stats_item.GPA }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </body>
</HTML>

It seems to work ok, but I'm questioning whether I'm on the right track with this method of doing things. Thanks.

5
  • 1
    Definitely do not do it this way. Create a file like students.php and then use $http in an Angular service to fetch the data. Commented Apr 14, 2016 at 18:24
  • Ok, so I jumped ahead too soon. I'm too novice in AngularJS to understand what you're saying. Conceptually, I get it, I think; PHP output json-encoded data and I make that my model? Commented Apr 14, 2016 at 18:31
  • 1
    Your Angular would looks something like this: jsfiddle.net/cmnv20ps And the students.php file would echo out the json_encoded data and exit Commented Apr 14, 2016 at 18:33
  • Thanks! I can't mark this question as answered, but thanks. Commented Apr 14, 2016 at 18:35
  • this was a good example for me: github.com/lucentx/angular-crud Commented Apr 14, 2016 at 19:50

1 Answer 1

1

Basically you want to make a call to a separate php file, which runs the query and echos a JSON encoded array for the Angular request to use.

Here is an example fiddle of the Angular side: https://jsfiddle.net/cmnv20ps/

function StudentsService($http) {
  var service = {
     getStudents: getStudents
  };

  return service;

  function getStudents(fname) {
     return $http.get('students.php', {
        params: {
           fname: fname
        }
     }).then(function(response) {
        return response.data;
     });
  }
}

function Controller(StudentsService) {
  var vm = this;

  StudentsService.getStudents('Ro').then(function(data) {
     vm.students = data.students;
  });
}

PHP Example:

$fname = $_GET["fname"];
$sql = $db->prepare("select * from students where fname like :fname");
$sql->execute(array("fname"=>"%" . $fname . "%"));
$res = $sql->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(array("students"=>$res));
Sign up to request clarification or add additional context in comments.

Comments

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.