1

I am trying to connect my angularjs application to a simple php script which is simply returning a sql query from sqlite3 database.

Here is my PHP script:

<?php
 date_default_timezone_set('UTC');
try {
        $objDb = new PDO('sqlite:../dbase/shopper');
        $objDb -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $sql = "SELECT item.* ,
                        t.name AS type_name
                        FROM items item
                        INNER JOIN types t
                        ON t.id = item.type
                        ORDER BY item.date ASC";

        $result = $objDb->query($sql);

        if(!$result) {
                throw new  PDOException("The result returned no object");
        }
        $result->setFetchMode(PDO::FETCH_ASSOC);
        $items = $result->fetchAll();

        $sql = "SELECT *
                        FROM types
                        ORDER BY id";
        $result = $objDb->query($sql);
        echo var_dump($result);
        if(!$result) {
                throw new  PDOException("The result returned no object");
        }
        $result->setFetchMode(PDO::FETCH_ASSOC);
        $types = $result->fetchAll();

        echo json_encode(array(
                'error' => false,
                'items' => $items,
                'types' => $types
        ), JSON_HEX_TAG | JSON_HEX_APOS |JSON_HEX_QUOT |JSON_HEX_AMP );

} catch (PDOException $e) {
        echo json_encode(array(
                'error' => true,
                'message' => $e->getMessage()
        ),JSON_HEX_TAG | JSON_HEX_APOS |JSON_HEX_QUOT |JSON_HEX_AMP );
}

When I check the php file address I can get the result :

object(PDOStatement)#3 (1) { ["queryString"]=> string(41) " SELECT * FROM types ORDER BY id " }
{"error":false,"items":[{"id":"1","item":"Butter","qty":"1","type":"1","done":"0","date":"2014-10-06 02:45:51","type_name":"Qty"}],"types":[{"id":"1","name":"Qty"},{"id":"2","name":"Kg"}]}

If I use angularjs I get undefined results.

.controller('ShoppingListController', function($scope, $http, $log ){ 
    $scope.types = [];
    $scope.items = [];

    $scope.item = '';
    $scope.qty = '';
    $scope.types = '';

     $scope.select = function( ) {

        $http({method: 'GET',url: 'mod/select.php'})
            .success(function(data){
                    console.log(data)
                    $scope.items = data.items;


                if(data.types) {

                    $scope.types = data.types;
                    $scope.type = $scope.types[0].id;

                }
            })
            .error(function(data,status,header){
                throw new Error('Something went wrong with selecting record');
            });
     };

     $scope.select();

});

console.log(data) shows :

object(PDOStatement)#3 (1) {
  ["queryString"]=>
  string(41) " SELECT * 
            FROM types 
            ORDER BY id "
}
{"error":false,"items":[{"id":"1","item":"Butter","qty":"1","type":"1","done":"0","date":"2014-10-06 02:45:51","type_name":"Qty"}],"types":[{"id":"1","name":"Qty"},{"id":"2","name":"Kg"}]} 

How can I fix this ?

3
  • Return a JSON response to the client and console.log() the data not the $scope.items Commented Oct 6, 2014 at 7:31
  • If you check the php link does not lines 40 -44 do that job ? Commented Oct 6, 2014 at 7:32
  • can you check the console.log(data) I have added to my question. Commented Oct 6, 2014 at 7:41

2 Answers 2

4

You must return a JSON response. Fetch an associative array from your database and return this:

echo json_encode($db_query);

In Angular, you can then set the scope equal to the response ex:

$scope.items = data.items;

You can then access this in your view (be sure to have ng-controller="ShoppingListController").

To iterate over the data:

ng-repeat="item in items"

You can then access each piece via item.id or whatever your key in the array may be.

Also, no need to set $scope.items at the top.

Edit:

.controller('ShoppingListController', function($scope, $http, $log) {
    function select() {
        $http.get('mod/select.php')
            .success(function(data) {
                $scope.items = data.items;

                if(data.types) {
                    $scope.types = data.types;
                    $scope.type = $scope.types[0].id;
                }
            });
    }

    select();

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

9 Comments

Noah , inside my question there is a php file pastebin link and yes I have those in my views and controllers. I can see the json also when I try php file and console.log data but I cant get for eg "data.items" or "data.type[0].id"
Since you're not calling the function in from the view, try my edit.
While you're at it, post your HTML augmented with Angular.
plnkr.co/edit/fuCIxKvK8voXfHu0DuTy?p=info .. here it is except for php .. php is in the question
yes still I get undefined when I try console.log(data.items).. console.log(data) gives me my last edit.
|
0

Remove the var_dump(); And BTW you don't need to echo with var_dump(), it already appends to the output buffer. The var_dump() makes your response invalid JSON.

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.