Pregunta

I need to count a table in a mysql database, and for this I need to use php. I use the following code, counttable.php:

$query = "SELECT COUNT(*) FROM table";
$result = mysqli_query($connection, $query);

$count = (string)$result;
echo $count;

mysqli_close();

My plan is then to use the following Angular code to fetch the result:

myApp.factory("count", function($http) {
    return $http.get('counttable.php');
});

In my controller I use the success and error functions of the factory to control the result.

count.success(function(data) {
    $scope.data = data;
});

count.error(function(data) {
    console.log("Count failed.");
});

When I run my webpage, it will say "Count failed." in the console. I have tried encapsulating the php $count variable as JSON with json_encode, but this only gave me an empty object. I am guessing there might be a simple answer to this, but I just cant see it.

Please help, any answer is highly appreciated! Thanks.

¿Fue útil?

Solución 3

Thanks for the replies! I could however not figure out the problem. I stumpled upon this question, and I thought this was the solution to my problem. However, this did not work either, I was able to get success from the $http.get, but the factory did not produce any data.

I am really clueless as to what the problem is, but I managed to do a "workaround" to get what I wanted; instead of doing the COUNT(*) query, I used SELECT name FROM table. Then I applied the json_decode, and passed the array to $http.get, which it would glady accept. Then I just found the length of the array like this:

$scope.count = 0;
count.success(function(data) {
    $scope.count = data.length;
});

And now it works..

Thanks again!

Otros consejos

Assuming you're running your angular application on localhost, e.g.

http://localhost/myapp/

then executing $http.get('counttable.php') would result in a request to

http://localhost/myapp/counttable.php

simply try to put the above url into your browser and evaluate the error message it provides you. Also look into the logs of your webserver.

to get more information on the request/response communication between your browser and the server, you can use a network analyser like the one included in chrome (http://net.tutsplus.com/tutorials/chrome-dev-tools-networking-and-the-console/), which you then can also use to see how your angular application behaves.

Enriching your console output can also be helpful

console.log('Count failed', data);

The code seems ok. Try:

console.log(data)

on the error function, so you can see what php echos.


Another approach is to use:

count.then(function(response) {
    console.log(response);
};

When you use then you can have the whole http web response, which contains the data, status, headers and config. This way you would be able to debug better.

Or you could just use:

success(function(data, status, headers, config)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top