Creating a Google Line Chart from MYSQL data - javascript

My aim is to create multiple line charts on the same graph using data i pull from mysql database.
I have the code in place but I'm missing a step therefore not getting the output I expect. Here's my code:
<?php
$results = array('cols' => array (array('label' => 'Date', 'type' => date'),
array('label' => 'Amount', 'type' => 'number')
),
'rows' => array()
);
$query = $db->prepare('SELECT * FROM Claims GROUP BY EXTRACT(MONTH FROM ClaimDate ) , EXTRACT( YEAR FROM ClaimDate ) ');
$query->execute();
$rows1 = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($rows1 as $row)
{
$ClaimDate = DateTime::createFromFormat('Y-m-d H:i:s', $row['ClaimDate'])->format('Y-m-d');
$dateArr = explode('-', $ClaimDate);
$year = (int) $dateArr[0];
$month = (int) $dateArr[1] - 1;
$day = (int) $dateArr[2];
$results['rows'][] = array('c' => array(array('v' => "Date($year, $month, $day)"), array('v' => $row['amount'])
));
}
$json = json_encode($results, JSON_NUMERIC_CHECK);
// print_r($json);exit;
?>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = new google.visualization.DataTable(<?php echo json_encode($json); ?>);
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, {width: 400, height: 240});
}
</script>
<div id="line_chart"></div>
So that's my code. This is the json that is passed to the chart from the database:
{"cols":[{"label":"Date","type":"date"},{"label":"Amount","type":"number"}],"rows":[{"c":[{"v":"Date(2015, 5, 23)"},{"v":6000}]},{"c":[{"v":"Date(2016, 5, 23)"},{"v":16000}]},{"c":[{"v":"Date(2015, 6, 23)"},{"v":10000}]},{"c":[{"v":"Date(2016, 6, 23)"},{"v":10000}]},{"c":[{"v":"Date(2015, 7, 23)"},{"v":5000}]},{"c":[{"v":"Date(2016, 7, 23)"},{"v":60000}]}]}
And below is the line chart that is output:
line chart output from above code
This is not what I want. My end goal is to get graph that displays multiple line charts(depending on the number of years present) with all the months displaying on the X-axis with the amount displaying on the Y-axis. This is the closest thing I've seen that resembles what I want to achieve:
linechart
The above image shows what I want to achieve. Like stated before, the months on the X-axis with the amount on the Y-axis. then the 'values' would be the years that have been returned from the query i.e. every year will have its own line chart
I'm a bit stuck on this and would like to request for guidance on how to accomplish this
Additional request
SIDU has tried to provide assistance by recommending I use the svg charts. Appreciated but can't this be done using google charts?

This would be easy with Topnew SVG Charts:
http://topnew.net/cms/cms_chart.php?data=ymd,Hit,IP;2016-01-01,2000,1000;2016-02-05,3000,1800;2016-03-20,4000,3000&chart=line&fmt=str_xss&xFormat=date|M
If you download the 9k topnew svg chart, you can call it in the following way instead:
<?php
include 'topnew_svg_chart.php';
$data = [
'Hit' => [
'2016-01-01' => 12345,
'2016-02-03' => 12345,
],
'IP' => [
'2016-01-01' => 2345,
'2016-02-03' => 2345,
]
];
$init = [
'chart' => 'line',
'xFormat' => 'date|M',
];
cms_chart($data, $init);

Related

laravel array data fill into google chart

Here is my array fetched from database. I need to that array data fill into google data chart. I tried few ways but I couldn't do that. please some one help me to do that.
code// dd($dates);
here dataTable.addRows section I need to replace, 1st picture displaying dataList.
please help me.
viewerController.php
public function show(){
$dates = collect();
foreach( range( -6, 0 ) AS $i ) {
$date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
$dates->put( $date, 0);
}
// Get the post counts
$persons = Person::where( 'created_at', '>=', $dates->keys()->first() )
->groupBy( 'date' )
->orderBy( 'date' )
->get( [
DB::raw( 'DATE( created_at ) as date' ),
DB::raw( 'COUNT( * ) as "count"' )
] )
->pluck( 'count', 'date' );
// Merge the two collections; any results in `$posts` will overwrite the zero-value in `$dates`
$dates = $dates->merge( $persons );
return view('layouts.chart',compact(['dates']));
}

How to parse a JSON data that has been received by a PHP scipt

I have sent data from my php script using `json_encode' function.
if I console.log(resp) below is the O/P I get.
data: "{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}" status: "success"
however, if I console.log(resp.data) I get the below data
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}
Now I'm trying to display this data in the data tables for which I am using the below code.
$('#grpList').DataTable().row.add([
resp.data.dept_name,
resp.data.city_name,
resp.data.emp_id,
resp.data.emp_name
]).draw(false);
I'm receiving the following error
DataTables warning: table id=grpList - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
when I am single handed displaying only console.log(resp.data.dept_name) it says undefined
I'll be having multiple JSON response if the data increases, for now, I only have two. I'm not able to figure out how to display multiple data using a loop and appending it to the data table.
I'm using below php code to generate JSON
$jsonArray = "";
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$jsonArray .= json_encode(
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
Because resp.data is an array of objects. You need to get the index first - let's say index 0, or the first object in the array:
$("#grpList").DataTable().row.add([
resp.data[0].dept_name,
resp.data[0].city_name,
resp.data[0].emp_id,
resp.data[0].emp_name
]).draw(false);
And if you want the second object:
$("#grpList").DataTable().row.add([
resp.data[1].dept_name,
resp.data[1].city_name,
resp.data[1].emp_id,
resp.data[1].emp_name
]).draw(false);
Of course, row.add() accepts an array argument as well - so this would work too:
$("#grpList").DataTable().row.add(resp.data).draw(false);
The issue is on server side.
You define $jsonArray as a string ! That's wrong.
Try this instead:
$jsonArray = []; // An ARRAY here!
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
array_push($jsonArray, json_encode( // Use array_push here
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
EDIT
I don't if the above works... Since I did not test it.
But here's how I would have writen it (I guess you'll have more chances with it):
$jsonArray = [];
if($data->num_rows > 0) {
while($row = $data->fetch_assoc()) {
// A temp array to rename the one of the keys...
$tempArray = [];
$tempArray = ["dept_name"] = $row['department_name'];
$tempArray = ["city_name"] = $row['city_name'];
$tempArray = ["emp_id"] = $row['emp_id'];
$tempArray = ["emp_name"] = $row['name'];
// Push to the jsonArray now...
array_push($jsonArray,$tempArray);
}
// And finally the result array... To be json encoded
$result = [];
$result = ["status"] = "success";
$result = ["data"] = jsonArray;
echo json_encode($result);
}
Note that without renaming one key and if there's only 4 data per rows from the DB... You could have done array_push($jsonArray,$row); directly, without using the $tempArray.
So try this... AND then apply Jack's answer. ;)

Unable to construct json datatable for Google charts

I've been stuck for quite some time on this problem now. I have looked around a lot but I can't seem to figure out the answer. See the link below for the reference on google developers.
https://developers.google.com/chart/interactive/docs/reference#dataparam
I have this PHP script which pulls data from my DB and then builds the JSON.
My code is as follows :
<?php
header('content-type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin:*');//Include this header to make the requests cross-origin
include 'dbconnect.php';//File for database connection
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Check if query GET parameters are defined
if(isset($_GET['date1']) && isset($_GET['date2'])){
$parm1=$_GET['date1'];
$parm2=$_GET['date2'];
//We build the metadata node of our json object with chart info / update time / chart title
//date_default_timezone_set('Etc/GMT+8');
//$date = date('Y-m-d H:i:s');
//$array['meta'][]=array('title'=>'Sales data for year'.$parm1.'-'.$parm2);
//$array['meta'][]=array('LastUpdated'=>$date);
//$array['meta'][]=array('Info'=>'This chart displays sales data on an annual basis');
$array['data']['cols'][]=array('label'=>'2008','type' => 'number');
$array['data']['cols'][]=array('label'=>'2009','type' => 'number');
}else{
echo "No data available";
}
$sql = "CALL TEST('$parm1','$parm2');";
//We run the query, store all rows in an associative array, then json_encode it
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 0;
while($row = $result->fetch_row()) {
$array['data']['rows'][]= array(
'c' => array(
array('v'=>intval($row[$i]))
));
echo $row[1];
$i++;
}
}else {
echo "0 results";
}
//unset($array['data']['rows'][0]);
echo $_GET['callback'].'('.json_encode($array).')';
$conn->close();//We close the database connection here
?>
The json output from this php script is as follows :
{
data: {
cols: [{
label: "2008",
type: "number"
}, {
label: "2009",
type: "number"
}],
rows: [{
c: [{
v: 3016207
}]
}]
}
}
My first problem is that in the c node, only one value is added, when there should be two v:{object}. The accepted format afaik should be in my particular case, two v:{object} nested in the c:[array]. I have a strong feeling that json_encode() is failing to build a complex JSON, but I've thrown much tougher stuff to it in the past and it worked. Can anyone help me ? Please :o
EDIT : The expected json format is :
{
data: {
cols: [{
label: "2008",
type: "number"
}, {
label: "2009",
type: "number"
}],
rows: [{
c: [{v: 3016207 },{v: 3000528}]
}]
}
}
My query is returning these :
+---------+---------+
| 2008 | 2009 |
+---------+---------+
| 3016207 | 3000528 |
+---------+---------+
So basically the second column's value is not being inserted :/
Whoever came up with that JSON format should be fired. Looks like someone was trying on purpose to make things difficult.
But it's not hard to generate if you understand what the database function return values are and how to manipulate those arrays. For example: you were looping over your result set, even though it always has a single row, but you had no loop over the columns. Then you were trying to fill in your c element with a single value $row[$i] and wondering why it was only a single value. (I suspect you may be misunderstanding how the $var[] construct works.) Read up on these functions if you want to have success in this. You're still vulnerable to SQL injection attacks, by the way.
Anyway, this is obviously untested but should at least get you started.
$sql = "CALL TEST('$parm1','$parm2')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
foreach ($row as $name=>$val) {
$array['data']['cols'][] = array('label'=>$name, 'type'=>'number');
$c[] = array("v"=>$val);
}
$array['data']['rows'] = array(array('c'=>$c));
} else {
echo "0 results";
}

PHP json format encoding

I've got the following code:
$data = array(
"1421852400000" => "100",
"1421856000000" => "110",
);
$newData = json_encode($data);
echo $newData;
This is what comes out (using the PHP code above)
{"1421852400000":"100","1421856000000":"110"}
But what I really need is the array in this format:
[
[1421852400000, 100],
[1421856000000, 110],
[1421859600000, 125]
]
Also, the first value is a timestamp (being used in Flot charts) and the second value is for the y axis of the graph.
In javascript I get these values like this:
var visit = JSON.parse(xmlhttp.responseText);
When I simply display the desired format it works, but when I try the PHP things it's giving me some odd results..
The problem is that when I use a PHP array and encode it then echo that and fetch it with Ajax and parse it with js it's not in the right format and thus it does not work..
How would I get the desired result? Thanks in advance!
This Is what you should put in the $data.
$data = array(
array("1421852400000", "100"),
array("1421856000000","110"),
);
$newData = json_encode($data);
echo $newData;
If you really need to display something similar to this:
[
[1421852400000, 100],
[1421856000000, 110],
[1421859600000, 125]
]
Change $data to something like this:
$data = array(
array(1421852400000, 100),
array(1421856000000, 110)
);

Google charts : date with json

I am using google charts and i have a problem to pass the date from php to javascript
I use this :
PHP :
$dataArray = array();
while ($resultat = $resultats->fetch_array(MYSQLI_ASSOC))
$thedate = "(".$year.", ".$month.")";
$fixe = "12";
$variable = "14";
$dataArray[] = array($thedate, (int) $fixe, (int) $variable);
JS :
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Taux fixes');
data.addColumn('number', 'Taux variables');
data.addRows(<?php echo json_encode($dataArray); ?>);
The error is :
Uncaught Error: Type mismatch. Value (2014, 1) does not match type date in column index 0
Does someone know how to send the date ? In which format ?
Google charts want a "new Date(2012, 03)" in JS
Thanks.
When using JSON, the proper format for dates is a string like this: 'Date(year, month, day)' (note there is no new keyword used in the string), where month is zero-indexed (so January is 0 not 1). The only DataTable construction method that supports inputting dates in this fashion is passing a JSON representation of the DataTable directly to the constructor:
var data = new google.visualization.DataTable(<?php echo json_encode($dataTable, JSON_NUMERIC_CHECK); ?>);
This requires reconfiguring your PHP a bit to construct a proper DataTable JSON string. You need to create an associative array with 'cols' and 'rows' keys. The 'cols' key sets the columns for your DataTable, and the 'rows' key contains the rows of data:
$dataTable = array (
'cols' => array (
array('type' => 'date', 'label' => 'Date'),
array('type' => 'number', 'label' => 'Taux fixes'),
array('type' => 'number', 'label' => 'Taux variables')
),
'rows' => array()
);
while ($resultat = $resultats->fetch_array(MYSQLI_ASSOC)) {
// put results in $year, $month, $fixe, $variable
$month = $month - 1; // correcting for javascript's 0-indexed months
$dataTable['rows'][] = array('c' => array(
array('v' => "Date($year, $month, 1)"),
array('v' => $fixe),
array('v' => $variable)
));
}

Categories

Resources