How to create a dynamic number of datasets based on DB values - javascript

My goal is to render a graph in PHP using CanvasJS but with multiple datasets dynamically generated based on the values in a DB. Generating this graph with only 1 dataset was working just fine, making it "dynamic" seems to be a challenge.
For 1 dataset I used the code below:
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
Where $dataPoint is send to the JS code
<script type="text/javascript">
$(function () {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
type: "line",
dataPoints: <?php echo json_encode($dataPoint, JSON_NUMERIC_CHECK); ?>
}
]
});
chart.render();
});
</script>
So far, so good, so, next step is to extend this to multiple datasets. In this case, for each user in the view "completedgames" we will create a new dataset $datapoint and each $datapoint will be added to the overal dataset $datapoints as shown below:
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
array_push($dataPoints, $dataPoint);
$dataPoint = array();
}
Where $dataPoints is the value now send to the same JS code as shown in above. Unfortunately this is where it goes wrong. data array_push() function doesn't feel right but I have no idea what the alternative is.
So, I hope this is sufficient information, all information is welcome and thanks in advance!

You have a few different problems, first when appending the data I would do this:
$dataPoint[] = array("x"=> $i , "y"=> $score);
Also I would get rid of this as it seems to be clearing out $dataPoint and might actually be creating additional levels in the array.
array_push($dataPoints, $dataPoint);
$dataPoint = array();

This code creates a $charts variable which looks like the data array in your javascript chart definition, rather than making a representation of just the dataPoints array. That should allow you to have as many data sets as you want.
$charts = [];
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$dataPoint = [];
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
array_push($charts, array(
"type" => "line",
"dataPoints" => $dataPoint
));
}
<script type="text/javascript">
$(function () {
var chart = new CanvasJS.Chart("chartContainer", {
data: <?php echo json_encode($charts, JSON_NUMERIC_CHECK); ?>
});
chart.render();
});
</script>

Using James' input I was able to make my Graph with multiple lines. Just needed to reset the counter and $dataPoint array: here is the working code:
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
json_encode($dataPoint, JSON_NUMERIC_CHECK);
$i++;
}
//array_push($dataPoints, $dataPoint);
// $dataPoint = array();
array_push($charts, array("type" => "line", "dataPoints" => $dataPoint));
$dataPoint = array();
$i = 0;
}
Thanks for all your inputs!

Related

How to retrieve Json Data and display on Chart.Js

Hello everyone I am trying to retrieve some data from data.php then allowing my app.js to display the data via Chartjs.
The data that I want to display is feedbackrowcount & complainrowcount
Which I already did a query to retrieve what I want from mysql.
Below is my data.php that does the query and the json data
<?php
//setting header to json
header('Content-Type: application/json');
$mysqli = mysqli_connect('localhost','root','','customercaremodule');
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query1 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Feedback'");
$Countsql1 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Feedback'";
//execute query
$result1 = $mysqli->query($query1);
$res1 = mysqli_query($mysqli,$Countsql1);
$value1 = mysqli_fetch_assoc($res1);
$feedbackrowcount = $value1['total'];
//loop through the returned data
$data1 = array();
foreach ($result1 as $row) {
$data1[] = $row;
}
//free memory associated with result
$result1->close();
//query to get data from the table
$query2 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Complain'");
$Countsql2 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Complain'";
//execute query
$result2 = $mysqli->query($query2);
$res2 = mysqli_query($mysqli,$Countsql2);
$value2 = mysqli_fetch_assoc($res2);
$complainrowcount = $value2['total'];
//loop through the returned data
$data2 = array();
foreach ($result2 as $row) {
$data2[] = $row;
}
//free memory associated with result
$result2->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data1);
print json_encode($data2);
print json_encode($feedbackrowcount);
print json_encode($complainrowcount);
?>
This is app.js that display the chart. I believe the Data: is the key to not being able to display the chart on my webpage. Please help me to write the statement needed to retrieve data from data.php to app.js. Thank you so much!
$.getJSON('http://localhost/customercare/data.php', function(data) {
console.log(data);
});
var oilCanvas = document.getElementById("oilChart");
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 18;
var feedbackvscomplainData = {
labels: [
"Feedback",
"Complain"
],
datasets: [
{
data:
backgroundColor: [
"#FF6384",
"#FF6300"
]
}]
};
var pieChart = new Chart(oilCanvas, {
type: 'pie',
data: feedbackvscomplainData
});

PHP variables in Javascript doesn't work

I am trying to show fetched data in Google charts, but PHP variables inside the javascript are not echoed.. If I echo variables outside of the javascript all works fine, so I suspect that something must be wrong in my javascript.. I double-checked everything but I can't figure our where is the issue..
The code does not show any errors!
This is the output in browser source..
['Active Posts',$post_counts],['Categories',$category_counts],['Users',$user_counts],['Comments',$comment_counts],
Any suggestion?
Thank you
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Data', 'Count'],
<?php
$data_text = ['Active Posts', 'Categories', 'Users', 'Comments'];
$data_count = ['$post_counts', '$category_counts', '$user_counts', '$comment_counts'];
for($i = 0; $i < 4; $i++) {
echo "['$data_text[$i]'" . "," . "$data_count[$i]],";
}
?>
]);
var options = {
chart: {
title: '',
subtitle: '',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
Since you're already using PHP to output data for JS, you can just use json_encode to convert your ARRAY to JSON data.
<?php
$data = [
'Data' => 'Count',
'Active Posts' => $post_counts,
'Categories' => $category_counts,
'Users' => $user_counts,
'Comments' => $comment_counts
];
$json = json_encode($data);
?>
var data = google.visualization.arrayToDataTable("<?php echo $json; ?>");
Remove quotes from php variables,
Use this,
$data_count = [$post_counts, $category_counts, $user_counts, $comment_counts];
instead of,
$data_count = ['$post_counts', '$category_counts', '$user_counts', '$comment_counts'];

How do I create a C3 Chart Line Graph from JSON data?

I need help for a school project. I have been able to pull data from a mySQL database into an array and encoded into JSON, which displays fine. Now, I need help with passing the JSON data to C3 to produce a chart (if possible on the same page).
What I've done so far:
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );
You need to create two separate array, one for your data and one for dates that you want to show on x-axis and then pass that array to java script.
here is full working example
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$valuesArray = array();
$datesArray = array();
$valuesArray[] = 'Oil';
$datesArray[] = 'x';
while ($row = $result->fetch_assoc()) {
$datesArray[] = $row['production_date'];
$valuesArray[] = $row['oil'];
}
?>
<html>
<head>
<title>C3 Liner example</title>
<link href="c3_scr/c3.css" rel="stylesheet" type="text/css" />
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="c3_scr/c3.js"></script><!-- load jquery -->
</head>
<body>
<div id="chart"></div>
<script>
var xAxisArr = <?php echo json_encode($datesArray); ?>;
var dataArr = <?php echo json_encode($valuesArray, JSON_NUMERIC_CHECK); ?>;
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
xAxisArr,
dataArr
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});
</script>
</body>
</html>

passing array data from PHP to Javascript

I am fetching an array from a MySQL result into a array variable. I can successfully use a simple php echo line in the javascript beneath to grab the first $row element, but I want to use json_encode to get the whole array at once.
When I do this and try to set a javascript var to the first array element something goes wrong and even the single var method stops working.
<?php
.
.
.
while($row = $result->fetch_array(MYSQLI_NUM)) {
$row1 = $row[0];
}
?>
<script type="text/javascript">
var RowArray = <?php echo json_encode($row); ?>;
var RA1 = RowArray[0];
window.alert(RA1);
var Row1 = '<?php echo $row1; ?>';
window.alert(Row1);
</script>
Make an array containing all the records:
$rows = [];
while ($row = $result->fetch_array(MYSQLI_NUM))
{
// do custom modifications to $row if neededed
$rows[] = $row; // push to array
}
Or just:
$rows = $result->fetch_all(MYSQLI_NUM);
And then use json_encode() with $rows.

How to load numbers into MySQLi fetch_array() function

Using following MySQLi and PHP snippet I can export the result in a numeric array as:
["8","188.396496","7.876766","69885005.45"]
Now I need to have the output in exact numeric format like (removing " " from the items)
[8,188.396496,7.876766,69885005.45]
and here is the code I have in PHP part
$query = "SELECT project, powerline, road, cost FROM `charts_econo_new`" ;
$results = $con->query($query);
if($results) {
while($row = $results->fetch_array(MYSQLI_NUM)) {
$json=json_encode($row);
}
}
$con->close();
echo $json;
?>
How can I do that?
Update
var req2 = $.ajax({
type: "POST",
data: data,
dataType: 'json',
url: "assets/tempchart.php"
});
req2.done(function(data) {
var cars = [];
cars.push(data)
console.log(cars[0]);
in this case the out out is [8,188.396496,7.876766,69885005.45] but I need to get ONLY 8 as cars[0] is 8.
if ($results) {
$row = $results->fetch_array(MYSQLI_NUM);
$row = array_map('floatval', $row); // Convert strings to numbers
echo json_encode($row);
}
The Javascript should be:
req2.done(function(data) {
var cars = [];
cars.push(data[0]);
console.log(cars[0]);
});
You just have to cast your results to float before calling json_encode :
$query = "SELECT project, powerline, road, cost FROM `charts_econo_new`" ;
$results = $con->query($query);
if($results) {
while($row = $results->fetch_array(MYSQLI_NUM)) {
// Cast to float
foreach($row as &$item) {
$item = (float) $item;
}
$json=json_encode($row);
}
}
$con->close();
echo $json;
(And you are only getting the last row of your table, because you overwrite the content of $json each time but if you only have one row in your table that can be ok)
Please try to use floatval() function to convert string from DB in float values.

Categories

Resources