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.
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!