Google Chart draws nothing using PHP array to send data - php

I'm trying to take a array from PHP code returned from my CodeIgniter model/controllers and display at my page view. But, the chart is not generated, maybe because it's not getting the right data.
Here's my code:
<?php
$data = array(
$generateChart['A'],
$generateChart['B']
);
json_encode($data);
?>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable();
data.addColumn('string', 'city');
data.addColumn('string', 'date');
data.addRows(<?php echo $data; ?>);
var options = {
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<div class="row">
<div id="piechart" style="width: 900px; height: 500px;" class="col-md-4">
</div>
If I send this: I receive the data everything fine!
Created a new question more specific about my problem: Google Charts won't work if passing JSON data but works with fixed data

couple things...
see the data format for PieChart
first column should be 'string'
second a 'number'
'date' column is invalid
the array format from the comment won't work
you need an array for each row, which should have a value for each column
something like...
Array(
[0] => Array(
[0] => 10 - TATUÍ
[1] => 12
)
[1] => Array(
[0] => 1 - CONCÓRDIA
[1] => 13
)
[2] => Array(
[0] => 928 - PONTA GROSSA
[1] => 14
)
)

Related

Googe Pie Chart PHP

Why can't I add data to my google pie chart?
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
<?php
foreach($piechartcaloy as $value){
echo "['".$value['product_name']."',".$value['TEST']."],";
}
?>
]);
var options = {
title: 'TOP 10 products'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart2'));
chart.draw(data, options);
}
it vanished the pie chart when i add the
<?php
foreach($piechartcaloy as $value){
echo "['".$value['product_name']."',".$value['TEST']."],";
}
?>
but if i add a normal
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['test',1]
]);
it work but why does my php does not working although i tried to print_r($data);die; my data array it shows like this
Array ( [piechartcaloy] => Array ( [0] => Array ( [product_name] => REG Okinawa [TEST] => 1 ) [1] => Array ( [product_name] => French Fries [TEST] => 0 ) ) )
It has values in it but why can't I populate it? What is wrong in my loop in the pie chart?
i already solved the answer and noticed that the array was having a space so i tried using trim(); and it works trim removes extra spaces that fix the problem.
here is the code i implement
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
<?php
foreach($piechartcaloy as $value){
echo "['".trim($value['product_name'])."',".trim($value['TEST'])."],";
}
?>
]);
var options = {
title: 'TOP 10 Fast Moving products'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart2'));
chart.draw(data, options);
}

PHP PDO Convert array to different format

I am trying to convert an array obtained by the code below using non-deprecated techniques with php pdo:
$stm = $conn->prepare("SELECT * FROM mysqltable");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
print_r($results);
to the following format required for fusioncharts to be used
[
{
label: "CJ Anderson",
value: "25"
},
{
label: "Imran Tahir",
value: "25"
},
...
...
]
The original array is as follows:
Array (
[0] => Array (
[Id] => 6
[Number] => 1234567890
[Visits] => 1
[Name] => John
)
[1] => Array (
[Id] => 7
[Number] => 1236549871
[Visits] => 9
[Name] => Jerry
)
[2] => Array (
[Id] => 8
[Number] => 2147483647
[Visits] => 3
[Name] => Jane
)
)
Any help would be appreciated, thanks.
EDIT:
As I commented below. I have a full php file that works if you put data in manually. I can't get it to work though when I put the $jsonEncodedData in though. Thoughts?
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- You need to include the following JS file to render the chart.
When you make your own charts, make sure that the path to this JS file is correct.
Else, you will get JavaScript errors. -->
<script src="fusioncharts/js/fusioncharts.js"></script>
</head>
<body>
<?php
try {
# MySQL with PDO_MYSQL
$mysql_host = 'host';
$mysql_database = 'table';
$mysql_username = 'user';
$mysql_password = 'pass';
$conn = new PDO("mysql:host=$mysql_host; dbname=$mysql_database", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
}
catch(PDOException $e) {
echo $e->getMessage();
}
// Form the SQL query that returns the top 10 most populous countries
// Execute the query, or else return the error message.
$stm = $conn->prepare("SELECT Name, Visits FROM mysqltable"); //WHERE Area :SelArea");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
include("fusioncharts.php");
$jsnarray = array();
foreach($results as $k => $v){
$jsnarray[] = array('label' => $results[$k]['Name'], 'value' => $results[$k]['Visits']);
};
$jsonEncodedData=json_encode($jsnarray);
new FusionCharts("type of chart",
"unique chart id",
"width of chart",
"height of chart",
"div id to render the chart",
"type of data",
"actual data");
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": //$jsonEncodedData}'); <---I tried to insert this after "data":but no results unlike if you put raw data**
[
{
"label":"Bakersfield Central",
"value":"880000"
},
{
"label":"Garden Groove harbour",
"value":"730000"
},
{
"label":"Los Angeles Topanga",
"value":"590000"
},
{
"label":"Compton-Rancho Dom",
"value":"520000"
},
{
"label":"Daly City Serramonte",
"value":"330000"
}
]
}');
// Render the chart
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
==============Edit 12/28/15==========
Tried the following code with no results, Question I have is shouldn't we end in "}" as they require that:
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": ' . $jsonEncodedData);
//}';
// Render the chart
print_r($columnChart);
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
I wanted to post the array differences as well between the "manual" method and the "fetch method (above in this edit).
With fetch:
FusionCharts Object ( [constructorOptions:FusionCharts:private] => Array ( >[type] => column2d [id] => ex1 [width] => 600 [height] => 400 [renderAt] => >chart-1 [dataFormat] => json [dataSource] => { "chart": { >"caption":"Harry's SuperMart", "subCaption":"Top 5 stores in last month by >revenue", "numberPrefix":"$", "theme":"ocean" }, "data": >[{"label":"John","value":"125"},{"label":"Jerry","value":"125"},{"label":"Jane","value":"125"}] ) [constructorTemplate:FusionCharts:private] => >[renderTemplate:FusionCharts:private] => )
With Manual Method (that works):
FusionCharts Object ( [constructorOptions:FusionCharts:private] => Array ( >[type] => column2d [id] => ex1 [width] => 600 [height] => 400 [renderAt] => >chart-1 [dataFormat] => json [dataSource] => { "chart": { >"caption":"Harry's SuperMart", "subCaption":"Top 5 stores in last month by >revenue", "numberPrefix":"$", "theme":"ocean" }, "data": [ { >"label":"Bakersfield Central", "value":"880000" }, { "label":"Garden Groove >harbour", "value":"730000" }, { "label":"Los Angeles Topanga", >"value":"590000" }, { "label":"Compton-Rancho Dom", "value":"520000" }, { >"label":"Daly City Serramonte", "value":"330000" } ] } ) >[constructorTemplate:FusionCharts:private] => >[renderTemplate:FusionCharts:private] => )
I see two differences offhand, the manual inserts spaces around "data" and the ending } parameter.
There is an automatic (and much much easier) way of doing this:
$stm = $conn->prepare('SELECT Name AS label, Visits AS value FROM mysqltable;');
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
$jsonEncodedData = json_encode($results);
echo $jsonEncodedData;
Output (locally tested):
[{"label":"Foo","value":"5"},{"label":"Bar","value":"15"}]
That way you can just use it like this:
$columnChart = new FusionCharts('...
...
"data": ' . $jsonEncodedData . '}');
Note the . '}' in the end.
Before Edit:
You could do something like this:
// This part is just for running purposes
$foo = array (
0 => Array (
'Id' => 6,
'Number' => 1234567890,
'Visits' => 1,
'Name' => 'John'
),
1 => array (
'Id' => 7,
'Number' => 1236549871,
'Visits' => 9,
'Name' => 'Jerry'
),
2 => array (
'Id' => 8,
'Number' => 2147483647,
'Visits' => "3", // Example to output quoted
'Name' => 'Jane'
)
);
$bar = array();
foreach($foo as $k => $v){
$bar[] = array('label' => $foo[$k]['Name'], 'value' => $foo[$k]['Visits']);
}
echo json_encode($bar);
Output:
[{"label":"John","value":1},{"label":"Jerry","value":9},{"label":"Jane","value":"3"}]
Compare with yours (from question) in one line:
[{label: "CJ Anderson",value: "25"},{label: "Imran Tahir",value: "25"},...]
Note: I assumed that value is represented by Visit and label by Name.
Read more about json_encode.
As a summary this is the piece that solved the issue including FirstOne's foreach statement:
$stm = $conn->prepare("SELECT Name, Visits FROM mysqltable"); //WHERE Area :SelArea");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
include("fusioncharts.php");
$jsnarray = array();
foreach($results as $k => $v){
$jsnarray[] = array('label' => $results[$k]['Name'], 'value' => $results[$k]['Visits']);
};
$jsonEncodedData=json_encode($jsnarray);
//print_r($jsonEncodedData);
new FusionCharts("type of chart",
"unique chart id",
"width of chart",
"height of chart",
"div id to render the chart",
"type of data",
"actual data");
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": ' . $jsonEncodedData . '}');
// Render the chart
print_r($columnChart);
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
Thanks for everyone's help in solving the issue.

google visualisation annotated timeline: how to set roles using PHP json roles

I am trying to plot two different time series using annotated timeline and PHP by adding roles - the second timeseries will have its own datetime type and role domain. Here is the index.php file:
<script type='text/javascript'>
google.load('visualization', '1', {'packages':['annotatedtimeline']});
google.setOnLoadCallback(drawChartSeptTEC);
function drawChartSeptTEC(){
var json = $.ajax({
url: "get_json_forecast.php",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(json);
var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
chart.draw(data, {displayAnnotations: true});
}
// setInterval(drawChartSeptTEC, 59000 );
</script>
and the server side:
<?php
$tempcols=array();
$tempcols[] =array('type' => 'datetime','role' => 'domain');
$tempcols[] =array('type' => 'number','role' => 'data','label'=>'polynomial');
$tempcols[] =array('type' => 'number','role' => 'interval');
$tempcols[] =array('type' => 'number','role' => 'interval');
$tempcols[] =array('type' => 'datetime','role' => 'domain');
$tempcols[] =array('type' => 'number','role' => 'data','label'=>'spectral');
$table['cols'] = $tempcols;
$rows = array();
$pg_result = pg_query($link,$query);
pg_close($link);
while ($row = pg_fetch_assoc($pg_result)) {
$temp = array();
$correctDateTime = substr_replace($row['time'], ( substr($row['time'],5,2) -1 ) ,5,2);
$temp[] = array('v' => "Date(".$correctDateTime.")");
$temp[] = array('v' => (float) $row['f2poly']);
$temp[] = array('v' => (float) $row['f2polydev']);
$temp[] = array('v' => (float) $row['f2polydev']);
$temp[] = array('v' => "Date(".$correctDateTime.")");
$temp[] = array('v' => (float) $row['f2spec']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
echo $jsonTable;
?>
The console error reports:
Error: each values column may be followed by one or two annotation columns. Column number 4 is of type datetime.
The visualisation works when I remove the second domain column.
The interval roles (that is the error bars) are not recognised as well. Which simplifies the question to: How do we configure roles using PHP?
annotated time line does not support roles. In order to achive the result, one needs to use another visualisation, for example:
....
google.load('visualization', '1', {'packages':['corechart']});
....
and to plot the data:
...
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
...
however, this chart does not support a second domain role, therefore you need to use one domain (or independent variable, say the x-axis) and use for y-values null if the domain x-values have no corresponding y-value for both data sets. In this case, and if you want to use lines, you need to set the option:
interpolateNulls: true,
in your draw() function.
Another option is to use dygraph which is faster than line chart.

Fetch Data from Oracle using OCI 8 and create Google Pie Chart

Fetch Data from Oracle:
echo "<br/>Self User data<br/>";
$curs = oci_new_cursor($conn);
$varin1 = "111"; //employee_id
$varin2 = "FEB-2015"; //month_year
$varin3 = "1";
$stid = oci_parse($conn, "begin WEEKLY_EMPLOYEE_DETAILS(:varIn1,:varIn2,:cursbv); end;");
oci_bind_by_name($stid, ":varIn1", $varin1);
oci_bind_by_name($stid, ":varIn2", $varin2);
oci_bind_by_name($stid, ":cursbv", $curs, -1, OCI_B_CURSOR);
oci_execute($stid);
oci_execute($curs); // Execute the REF CURSOR like a normal statement id
echo "<pre>";
while (($row = oci_fetch_array($curs, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
print_r($row) . "<br />\n";
}
oci_free_statement($stid);
oci_free_statement($curs);
Ouput of above code:
Self User data
Array
(
[EMPLOYEEID] => 111
[EMPLOYEENAME] => John Doe
[TOTAL_HOURS] => 24
[STATUS] => 1
[WEEK_ID] => 2
)
Array
(
[EMPLOYEEID] => 111
[EMPLOYEENAME] => John Doe
[TOTAL_HOURS] => 20
[STATUS] => 2
[WEEK_ID] => 3
)
Array
(
[EMPLOYEEID] => 111
[EMPLOYEENAME] => John Doe
[TOTAL_HOURS] => 40
[STATUS] => 2
[WEEK_ID] => 4
)
Google Pie chart Code:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Work', 'Hours per Day'],
['Week 1', 25],
['Week 2', 25],
['Week 3', 25],
['Week 4', 25]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
How can I show the data fetched in form of pie chart. If there are 5 weeks in a month it will display the pie chart slice likewise. Along with it, it should also display hours for that week which are coming in array.
The pie chart looks great. You could pass the php variables to javascript and use them in the array.
var week1 = <?php echo json_encode($week1['TOTAL_HOURS']); ?>;
etc..
var data = google.visualization.arrayToDataTable([
['Work', 'Hours per Week'],
['Week 1', week1],
['Week 2', week2],
['Week 3', week3],
['Week 4', week4]
]);
It would be cleaner to put these variables in an array, and do a check first how many weeks there are in the month. You could do the same for the daily hours by fetching the daily employee details from the oracle database (if they exist).
To read more about passing variables to javascript:
How to pass variables and data from PHP to JavaScript?

JSON from mySQL and Coloring in Google Charts

I would like to get some help with coloring data differently in with google chart. I'm trying to compare two domains with date and rank value.
If I leave out the 'domain' data and just have date and value data, it will display a chart with the date data on the y-axis and the value data on the x-axis. I would like to use the domain data in my table to differentiate the data I'm comparing, one domain in one color vs. another domain in another color in a bar chart with the legend identifying the domain.
Basically using the code below I get the following error:
All series on a given axis must be of the same data type
If there's different and or easier way of going about this let me know.
Table Structure:
Column Type Null Default Comments
date text No
value text No
domain text No
Here's what I use to change my mysql data into Google friendly JSON:
<?php
/* $server = the IP address or network name of the server
* $userName = the user to log into the database with
* $password = the database account password
* $databaseName = the name of the database to pull data from
*/
$host="127.0.0.1"; //replace with your hostname
$username="XXXXXXX"; //replace with your username
$password="XXX"; //replace with your password
$db_name="KYW_data"; //replace with your database
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name") or die ("cannot select DB");
mysql_select_db($db_name, $con);
// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
$query = mysql_query('SELECT date, value FROM KYW_Compete_rank');
$table = array();
$table['cols'] = array(
/* define your DataTable columns here
* each column gets its own array
* syntax of the arrays is:
* label => column label
* type => data type of column (string, number, date, datetime, boolean)
*/
array('label' => 'date', 'type' => 'string'),
array('label' => 'value', 'type' => 'number'),
array('label' => 'value', 'type' => 'string')
// etc...
);
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['date']);
$temp[] = array('v' => $r['value']);
$temp[] = array('v' => $r['domain']);
// etc...
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
Code for Displaying Google Chart:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "fetch.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
new google.visualization.BarChart(document.getElementById('visualization')).
draw(data,
{title:"Rank Standings",
width:600, height:400,
vAxis: {title: "Year and Month"},
hAxis: {title: "Rank"}}
);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="visualization"></div>
</body>
</html>
To get the legend to display two different series, you have to split your data into two columns. You can use SQL like this to split your data:
SELECT
date,
SUM(IF(<condition for series 1>, value, 0)) AS value_1,
SUM(IF(<condition for series 2>, value, 0)) AS value_2
FROM KYW_Compete_rank
GROUP BY date
and then populate your DataTable:
$table = array(
'cols' => array(
array('label' => 'date', 'type' => 'string'),
array('label' => 'value 1', 'type' => 'number'),
array('label' => 'value 2', 'type' => 'number')
)
'rows' => array()
);
while($r = mysql_fetch_assoc($query)) {
$data['rows'][] = array('c' => array(
array('v' => $r['date']),
array('v' => $r['value_1']),
array('v' => $r['value_2'])
));
}
echo json_encode($data, JSON_NUMERIC_CHECK);

Categories