My goal is to generate charts by utilizing data from MySQL within my JS file.
The process involves:
- Fetching data in my JS script by calling my PHP file.
- Successfully establishing a connection (PHP).
- Converting the data into JSON format.
- Retrieving the transformed data back in my JS file.
- Rendering and displaying the data on my HTML page/file.
Here is an example snippet of how I am displaying the data using AngularJS:
`<div ng-repeat="x in users" align="center">
<div class="col-md-4" >
<div class="showProfile">
{{x.TotalCall}}
</div>
</div>
</div>`
This is how my PHP code looks like:
<?php
$dbhost="localhost";
$dbuser="root";
$dbpass="";
$dbname="callstats";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $dbh->query("SELECT extension, COUNT(*) AS TotalCall, COUNT(CASE WHEN billsec >= 20 THEN billsec END) AS 'moreThanTwenty' FROM pbx GROUP BY extension");
$query = $query->fetchAll(PDO::FETCH_ASSOC);
$myJson = json_encode($query);
echo "{\"records\":".$myJson."}";
?>
And this is how my AngularJS file is structured:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("php/DBbitrix.php")
.then(function(response) {
$scope.users = response.data.records;
});
// additional charting logic goes here
});
If the data for the pieChart is [20,50,60,80,100], the visualization will be successful. I aim to use the values stored in the TotalCall table of my database in the "data : []" section.
Despite encountering challenges for the past few days, I have attempted various solutions such as using angular.foreach. However, incorporating the JSON data directly into my JS file remains elusive.
I've made efforts to inspect and log the values in the console with no luck:
var users = $scope.users;
console.log(users);
// additional console logs
Regrettably, the value returned is consistently "undefined," leaving me unable to access the desired data. As a learner of English, please forgive any errors in this post, as it marks my first contribution on Stackoverflow.