Display Vertical bar chart with grouped bars. - php

I am trying to create barchart using google charts. I want to display both Sales Orders and Sales Quotations total value each month. Now i have done it like this, it displays only orders value for each month that too in horizontal format. I am not getting how to show both the values using single barchart (vertically)
here is my code
$query = "SELECT MONTHNAME(last_modified) as month,
orders.sales_order_id,
orders.authorise, orders.company_id,
before_order_line_items.sales_order_id,
before_order_line_items.item,
before_order_line_items.uom,
SUM(before_order_line_items.total) AS 'Total',
before_order_line_items.tax from orders INNER JOIN
before_order_line_items ON
orders.sales_order_id ON
before_order_line_items.sales_order_id
where orders.order_quote = 'Order'
AND orders.authorise='Yes'
GROUP BY MONTH(orders.last_modified)
ORDER BY MONTH(orders.last_modified)";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result))
{
$myurl[] = "['".$row['month']."', ".$row['Total']."]";
}
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Month', 'Actuals'],
/* ['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]*/
<?php echo implode(",", $myurl);
?>
]);
var options = {
title: 'Orders',
vAxis: {title: '', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>

first, need to adjust sql to return both the values
then add columns to $myurl[]
$myurl[] = "['".$row['Month']."', ".$row['Quotes'].", ".$row['Orders']."]";
from there, draw the chart, but recommend using loader.js vs. older library jsapi
something like this should be close...
$query = "SELECT
MONTHNAME(last_modified) as Month,
SUM(case when orders.order_quote = 'Order' then before_order_line_items.total else 0 end) AS Orders,
SUM(case when orders.order_quote = 'Quote' then before_order_line_items.total else 0 end) AS Quotes
FROM orders
INNER JOIN before_order_line_items
ON orders.sales_order_id = before_order_line_items.sales_order_id
WHERE orders.authorise = 'Yes'
GROUP BY MONTH(orders.last_modified)
ORDER BY MONTH(orders.last_modified)";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {
$myurl[] = "['".$row['Month']."', ".$row['Quotes'].", ".$row['Orders']."]";
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Month', 'Quotes', 'Orders'],
<?php
echo implode(",", $myurl);
?>
]);
var options = {
title: 'Orders',
vAxis: {
title: '',
titleTextStyle: {
color: 'red'
}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>

Related

Error while fetching MySQL data for Google Charts "Data column(s) for axis #0 cannot be of type string"

The PHP code throws the error "Data column(s) for axis #0 cannot be of type string"
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year1', 'CountGiardiaPos', 'CountCryptoPos'],
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
if($result){
echo "CONNECTED TO CLOUD PRU DATABASE<br>";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
?>
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 1600px; height: 800px"></div>
</body>
</html>
If I run the code in a separate PHP file
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "['".$row[Year1]."', ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
I get the correct data:
['2003', 0, 207],['2005', 0, 29],['2006', 1, 59],['2007', 1, 148],['2008', 1, 109],['2009', 72, 71],['2010', 450, 261],['2011', 1934, 967],['2012', 662, 206],['2013', 627, 487],['2014', 735, 233],['2015', 720, 350],['2016', 855, 503],['2017', 836, 593],['2018', 983, 950],['2019', 920, 508],['2020', 291, 97],
Where is the error in the code?
the issue is that you're printing "CONNECTED TO CLOUD PRU DATABASE<br>" in the middle of your data array, here...
var data = google.visualization.arrayToDataTable([ // <-- ARRAY STARTS HERE
['Year1', 'CountGiardiaPos', 'CountCryptoPos'],
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
if($result){
// PRINTING THIS HERE WILL MESS UP YOUR ARRAY
echo "CONNECTED TO CLOUD PRU DATABASE<br>";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array()) {
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
}
}
?>
]); // <-- ARRAY ENDS HERE
but let's back up. first, it is not recommended to manually build json data by concatenating strings and variables.
echo "[".$row[Year1].", ".$row[CountGiardiaPos].", ".$row[CountCryptoPos]."],";
instead, build the array in php and use json_encode to print it on the page.
<?php
$result = mysqli_query($connection, "SELECT * FROM sqlAnnualPositives2");
$rows = array();
if ($result->num_rows > 0) {
// add column headings
$rows[] = array('Year1', 'CountGiardiaPos', 'CountCryptoPos');
// output data of each row
while($row = $result->fetch_array()) {
$rows[] = array($row[Year1], $row[CountGiardiaPos], $row[CountCryptoPos]);
}
}
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// use json_encode to build data table
var data = google.visualization.arrayToDataTable(<?php echo json_encode($rows); ?>);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 1600px; height: 800px"></div>
</body>
</html>

Multi line Google Line Chart, using data from mySQL db

I'm going through a bit of a learning process, in order to create a small database backed reporting system for my company.
The intent is to draw a multi line chart using Google Charts, based on a mysql database.
I've managed to get the data to echo from the mysql database, but it's not generating the chart. All I get is the echo, and a blank space where the chart should be. The echo is shown for debugging purposes.
Here is the code :
<?php include 'confile.php';
$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-03-02' ORDER BY time ASC";
$result = $conn->query($qry);
if($result === FALSE) {
echo mysql_errno($result) .": ". mysql_error($result) ."/n";
die(mysql_error());
}
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Time', 'type' => 'datetime'),
array('label' => 'Probe 1', 'type' => 'number'),
array('label' => 'Probe 2', 'type' => 'number'),
array('label' => 'Probe 3', 'type' => 'number'),
array('label' => 'Probe 4', 'type' => 'number')
);
while($r = mysqli_fetch_assoc($result)) {
$temp = array();
$temp[] = array($r['time']);
$temp[] = array($r['p1']);
$temp[] = array($r['p2']);
$temp[] = array($r['p3']);
$temp[] = array($r['p4']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?$jsonTable?>);
var options = {
title: 'Recorded Temperatures',
legend: {position: 'bottom' },
width: 800,
height: 600
};
var chart = new google.visualization.Table(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
And this is the 'echo' output
{"cols":[{"label":"Time","type":"datetime"},{"label":"Probe 1","type":"number"},{"label":"Probe 2","type":"number"},{"label":"Probe 3","type":"number"},{"label":"Probe 4","type":"number"}],"rows":[{"c":[["03:02:07"],["270.26"],["298.40"],["111.54"],["228.06"]]},{"c":[["03:28:42"],["273.23"],["190.43"],["245.69"],["283.21"]]},{"c":[["07:26:04"],["144.33"],["217.26"],["206.53"],["167.68"]]},{"c":[["12:13:20"],["153.15"],["277.23"],["167.20"],["240.88"]]}]}
This is test data, using a test query on the db. Once I understand the formatting to render the chart, it will be setup to allow the user to select which date to view, etc.
This was the closest existing question I can find, but doesn't seem to answer the question.
Not able to generate a Google Chart using MySQL table data as the data source
Following the answer of #MickMackusa, I managed to hack this together to get it to work, by ensuring the mysql/php array was output in a manner acceptable to Google Charts.
Thanks to #MickMacUSA for his assistance.
The final, working code, is below.
<?php include 'confile.php';
$qry = "SELECT time,p1,p2,p3,p4 from $db WHERE date = '2016-04-16' ORDER BY time ASC";
$result = $conn->query($qry);
if($result === FALSE) {
echo mysqli_errno($result) .": ". mysqli_error($result) ."/n";
die(mysqli_error());
}
$i = 0; //iteration counter - start at 0
$totalRows = mysqli_num_rows($result); // we need this to know when to change the output
$targetRows = $totalRows - 1; //row indies start from 0, not 1.
foreach ($result as $row){
$comTime = str_replace(":",",",$row['time']); // for each row, remove the : and put , in its place
if ($targetRows == $i) { // if the index is the same value as the target (ie, it's the last row)...
$temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."]". PHP_EOL;
} else {
$temp = "[[".$comTime."],".($row['p1']).",".($row['p2']).",".($row['p3']).",".($row['p4'])."],". PHP_EOL;
}
$i = $i + 1;
$rows[] = $temp;
}
$table = $rows;
$data = implode($table); //format the table as a single string, with line returns
//echo $i;
//echo $data;
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('timeofday','Time');
data.addColumn('number','Probe 1');
data.addColumn('number','Probe 2');
data.addColumn('number','Probe 3');
data.addColumn('number','Probe 4');
data.addRows([
<?php echo $data; ?> //dump the result into here, as it's correctly formatted
]);
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
Your number values must be formatted differently and you want timeofday not datetime.
According to: https://developers.google.com/chart/interactive/docs/reference#dataparam
Format your data to look like this:
{cols:
[
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows:
[
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
}
And you must echo it in the javascript:
change:
<?$jsonTable?>
to:
<?php echo $jsonTable; ?>
And put your javascript code block just before your </body> tag.
This is the full working code using the above data format that I tested on my server:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable(
{cols:[
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows:[
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
});
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
This is an alternative format that will be simpler/clearer/easier to build/comprehend using your mysqli results:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('timeofday','Time');
data.addColumn('number','Probe 1');
data.addColumn('number','Probe 2');
data.addColumn('number','Probe 3');
data.addColumn('number','Probe 4');
data.addRows([
[[03,02,07],270.26,298.40,111.54,228.06],
[[03,28,42],273.23,190.43,245.69,283.21],
[[07,26,04],144.33,217.26,206.53,167.68],
[[12,13,20],153.15,277.23,167.20,240.88]
]);
var options = {
title: 'Recorded Temperatures',
legend: { position: 'bottom' },
width: 900,
height: 500,
hAxis: { format: 'hh:mm:ss' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</body>
</html>
See the SO Demo provided by WhiteHat:
google.charts.load('current', {
callback: drawChart,
packages: ['corechart', 'table']
});
function drawChart() {
var data = new google.visualization.DataTable({cols: [
{"label":"Time","type":"timeofday"},
{"label":"Probe 1","type":"number"},
{"label":"Probe 2","type":"number"},
{"label":"Probe 3","type":"number"},
{"label":"Probe 4","type":"number"}
],
rows: [
{c:[{v:[03,02,07],f:'03:02:07'},{v:270.26},{v:298.40},{v:111.54},{v:228.06}]},
{c:[{v:[03,28,42],f:'03:28:42'},{v:273.23},{v:190.43},{v:245.69},{v:283.21}]},
{c:[{v:[07,26,04],f:'07:26:04'},{v:144.33},{v:217.26},{v:206.53},{v:167.68}]},
{c:[{v:[12,13,20],f:'12:13:20'},{v:153.15},{v:277.23},{v:167.20},{v:240.88}]}
]
});
var table = new google.visualization.Table(document.getElementById('chart_0'));
table.draw(data);
var options = {
title: 'Recorded Temperatures',
legend: {position: 'bottom' },
width: 800,
height: 600,
hAxis: {
format: 'hh:mm:ss'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_1'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_0"></div>
<div id="chart_1"></div>

How to iterate database values by date for google charts

I have seen similar questions but still do not understand how it woks.. I have this while loop looping my DB for dates, leads and sold. For each date in the DB I would like to show the daily leads and sold for each date in the DB in a line chart.
$sql = "SELECT * FROM customers WHERE source = 'website' ORDER BY date ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sold = $row['sold'];
$visit= $row['visit'];
$date= $row['date'];
}else{
}
}
Here is the chart script -
<script type="text/javascript">
google.charts.setOnLoadCallback(drawChartl);
function drawChartl() {
var data = google.visualization.arrayToDataTable([
['Date', 'Leads', 'Sold'],
['1st', 6, 2],
['2nd', 3, 1],
['3rd', 2, 3],
]);
var options = {
title: 'Internet Performance',
curveType: 'function',
legend: { position: 'top' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
<div id="curve_chart" style="width: 1900px; height: 500px"></div>
see following snippet...
need an array that holds all the data --> $json
then add each row to $json --> $dataRow
then write the result to the javascript --> data.addRows(<?= $jsonstring ?>);
try something like this, probably need to format the date too...
<?php
$json = array();
$sql = "SELECT * FROM customers WHERE source = 'website' ORDER BY date ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$dataRow = array(
$row['date'],
$row['visit'],
$row['sold']
);
array_push($json, $dataRow);
}
}
$jsonstring = json_encode($json);
?>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'callback': function () {
var data = google.visualization.arrayToDataTable([
[{type: 'string', label: 'Date'}, {type: 'number', label: 'Leads'}, {type: 'number', label: 'Sold'}]
]);
data.addRows(<?= $jsonstring ?>);
var options = {
title: 'Internet Performance',
curveType: 'function',
legend: { position: 'top' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
},
'packages': ['corechart']
});
</script>
<div id="curve_chart" style="width: 1900px; height: 500px"></div>

Highcharts - parse json series

Im using this to draw column highcharts jsfiddle
i use this to gt JSON:
<?php
$query = mysql_query("SELECT
sales_raport_all.from_date,
sales_raport_all.to_date,
sales_raport_all.konto,
SUM(sales_raport_all.saldo_sprzedazy),
SUM(sales_raport_all.wartosc_kosztowa),
SUM(sales_raport_all.marza),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date,
klienci_ax_all.sales_group
ORDER BY
sales_raport_all.from_date,
klienci_ax_all.sales_group");
$raw = array();
$dates = array();
while ($r = mysql_fetch_array($query)) {
$date = $r['from_date'];
if (!in_array($date, $dates)) $dates[] = $date;
$sales_group = $r['sales_group'];
$raw[$sales_group][$date] = intval($r['SUM(sales_raport_all.saldo_sprzedazy)']);
}
$data = array();
$data[0] = array('name' => "Date", 'data' => $dates);
foreach ($raw as $name => $d) {
$new_data = array('name' => $name, 'data' => array());
foreach ($dates as $date) {
$new_data['data'][] = isset($d[$date]) ? $d[$date] : 0;
}
$data[] = $new_data;
}
print json_encode($data);
in fiddle i use
chart3Options.series[0] = json[1];
...
is there a simple way to define all data in json? this data is variable and if i declare 11 variables and there will be only 7 then charts will not draw
JSON output for one date:
[{"name":"Date","data":["2014-01-01"]},{"name":"IN","data":[2580]},{"name":"KD","data":[5030]},{"name":"\u0141S","data":[12628]},{"name":"NN","data":[400]},{"name":"SG","data":[12979]},{"name":"TD","data":[15096]}]
// EDIT
i create new file:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'test',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'test'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("test2.php", function(json) {
options.xAxis.categories = json[0]['category'];
options.series[0] = {};
options.series[0].name = json[0]['name'];
options.series[0].data = json[0]['data'];
chart = new Highcharts.Chart(options);
});
});
</script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
and test2.php
<?php
$db_host = '******';
$db_user = '******';
$db_pass = '******';
$db_database = '******';
$link = mysql_connect($db_host,$db_user,$db_pass) or die('Nawiązanie połączenia z bazą danych nie było możliwe');
mysql_select_db($db_database,$link);
mysql_query("SET names UTF8");
$query = mysql_query("SELECT
sales_raport_all.from_date,
sales_raport_all.to_date,
sales_raport_all.konto,
SUM(sales_raport_all.saldo_sprzedazy),
SUM(sales_raport_all.wartosc_kosztowa),
SUM(sales_raport_all.marza),
klienci_ax_all.sales_group,
klienci_ax_all.nazwa
FROM
sales_raport_all
INNER JOIN
klienci_ax_all
ON
sales_raport_all.konto=klienci_ax_all.konto_odbiorcy
WHERE
YEAR(from_date) = YEAR(CURDATE())
GROUP BY
sales_raport_all.from_date,
klienci_ax_all.sales_group
ORDER BY
sales_raport_all.from_date,
klienci_ax_all.sales_group");
$result = array();
while($r = mysql_fetch_array($query)) {
$grupa = $r['sales_group'];
$datetime = $r['from_date'];
$result['name'][] = $datetime;
$result['category'][] = $grupa;
$result['data'][] = intval($r['SUM(sales_raport_all.saldo_sprzedazy)']);
}
$json = array();
array_push($json,$result);
print json_encode($json);
?>
JSON give me:
[{"name":["2014-01-01","2014-01-01","2014-01-01","2014-01-01","2014-01-01","2014-01-01"],"category":["IN","KD","\u0141S","NN","SG","TD"],"data":[2580,5030,12628,400,12979,15096]}]
Series looks greate but i dont know how to change category as in example http://jsfiddle.net/rubJS/
You can handle it in javascript. In other words, instead of defining variable for each <x,y> pair, return the data and let javascript construct the series.
For example, given your current output you can prepare X and Y values (in javascript) in separate arrays and write a function pushing these values into series. It can be done like this (using jQuery as an example):
function build_chart(x_values, y_values, options)
{
jQuery.each(x_values, function(item) {
options.xAxis.categories.push(x_values[item]);
});
var series = {
data: []
};
jQuery.each(y_values, function(item) {
series.data.push(parseInt(y_values[item]));
});
options.series.push(series);
chart = new Highcharts.Chart(options);
return chart;
}
Where variable options defines a chart template without series member (which is added by the above function)
EDIT
Following the edit in the question, here is the jsFiddle supporting it.
Note that the data in JSON is represented as array of arrays. First element in each array corresponds to the first category, second element in each array corresponds to the second category etc.
Apart from incorrect json format (which was mentioed) you need to push your dates as categorries in highcharts or use datetime type of axis, and then parse your date to timestamp.

generating graph with static data using Google Charts

I want to generate graph for my static data. I am using Google Chart for doing this. Here is the google 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([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
But i want to put my code in this. I am not getting how to do it. Here is my code
<?php
echo '<div align="center" style="width:100%; padding-top:20px;">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td class=tddash>10 latest purchase orders</td>
</tr>
<tr>
<td>';
$SQL = 'SELECT purchorders.orderno,
suppliers.suppname,
purchorders.orddate,
purchorders.deliverydate,
purchorders.initiator,
purchorders.requisitionno,
purchorders.allowprint,
purchorders.status,
suppliers.currcode,
currencies.decimalplaces AS currdecimalplaces,
SUM(purchorderdetails.unitprice*purchorderdetails.quantityord) AS ordervalue
FROM purchorders
INNER JOIN purchorderdetails
ON purchorders.orderno = purchorderdetails.orderno
INNER JOIN suppliers
ON purchorders.supplierno = suppliers.supplierid
INNER JOIN currencies
ON suppliers.currcode=currencies.currabrev
WHERE purchorders.orderno=purchorderdetails.orderno
GROUP BY purchorders.orderno,
suppliers.suppname,
purchorders.orddate,
purchorders.initiator,
purchorders.requisitionno,
purchorders.allowprint,
purchorders.status,
suppliers.currcode,
currencies.decimalplaces LIMIT 5';
$SalesOrdersResult2 = DB_query($SQL,$db);
$Total = 0;
echo '<table width="100%" celpadding="2" class="selection">';
echo '<tbody><tr><th> Supplier </th><th>Order Date</th><th>Delivery Date</th><th>Initiator</th><th>Order Total</th><th>Status</th></tr></tbody> ';
$k=0;
while ($row = DB_fetch_array($SalesOrdersResult2))
//while ($row = mysql_fetch_array($SalesOrdersResult))
{
if ($k == 1){
echo '<tr class="EvenTableRows">';
$k = 0;
} else {
echo '<tr class="OddTableRows">';
$k = 1;
}
$FormatedOrderValue2 = locale_number_format($row['ordervalue'],$row['currdecimalplaces']);
$Total += $row['ordervalue'];
//$FormatedOrderValue1 = locale_number_format($myrow['ordervalue'],$_SESSION['CompanyRecord']['decimalplaces']);
$FormatedOrderDate1 = ConvertSQLDate($row['orddate']);
$FormatedDelDate1 = ConvertSQLDate($row['deliverydate']);
echo ' <td> ' . $row['suppname'] . ' </td>';
echo ' <td>$FormatedOrderDate1</td><td>$FormatedDelDate1</td><td> ' . $row['initiator'] . ' </td><td>$FormatedOrderValue2</td><td> ' . $row['status'] . ' </td> ';
}
echo '<tr><td colspan="3">Total---</td><td colspan="2">$Total</td></tr></tbody>';
echo '</table></td>';
echo' </tr>
</table>
</div>';
Can somebody plz help me in this?
* EDITED *
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>';
echo ' <script type="text/javascript">
function drawChart() {
var jsonData = $.ajax({
url: "1getData.php",
dataType:"json",
async: false
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setColumns([0, 3]);
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, {width:400, height:240});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
</script>';
echo '</head>';
<div id="chart_div" ></div>
1getData.php
<?php
$PageSecurity=0;
include('includes/session.inc');
if (!isset($RootPath)){
$RootPath = dirname(htmlspecialchars($_SERVER['PHP_SELF']));
if ($RootPath == '/' or $RootPath == "\\") {
$RootPath = '';
}
}
$SQL = "SELECT workorders.wo, woitems.stockid, stockmaster.description, stockmaster.decimalplaces, woitems.qtyreqd, woitems.qtyrecd, workorders.requiredby, workorders.startdate
FROM workorders
INNER JOIN woitems ON workorders.wo = woitems.wo
INNER JOIN stockmaster ON woitems.stockid = stockmaster.stockid
ORDER BY workorders.wo";
$searchresult = DB_query($SQL, $db);
$table=array();
$table['cols']=array(
array('label'=>'ITEM', type=>'string'),
array('label'=>'Description', type=>'string'),
array('label'=> 'QTY Required', type=>'number'),
array('label'=>'QTY Outstanding', type=>'number')
);
$rows=array();
while ($row = DB_fetch_array($searchresult))
{
$qreq = locale_number_format($row['qtyreqd'],$row['decimalplaces']);
$qout = locale_number_format($row['qtyreqd']-$row['qtyrecd'],$row['decimalplaces']);
$temp=array();
$temp[]=array('v' => $row['stockid']);
$temp[]=array('v' => $row['description']);
$temp[]=array('v' => $row['qtyreqd']);
$temp[]=array('v' => ($row['qtyreqd']-$row['qtyrecd']));
$rows[]=array('c' => $temp);
}
$table['rows']=$rows;
$jsonTable = json_encode($table);
print $jsonTable;
?>
but it displays only two columns, where as i want to display 3
JAVA SCRIPT
<script type="text/javascript">
function drawChart() {
var jsonData = $.ajax({
url: "1getData.php",
dataType:"json",
async: false
}).responseText;
alert(jsonData);
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
view.setColumns([0,3]);
var chart = new google.visualization.ColumnChart(document.getElementById("chart_div"));
chart.draw(view, {width:400, height:240});
}
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
</script>
Your line view.setColumns([0, 3]) tells Google charts to only display the first and fourth column in your data. Add the columns you want to display to the array.

Categories