MSSQL/PHP to HighChart via JSON - php

Im trying to get data from my SQL server via php, and output it as JSON, so i can use it for HighCharts. So far i can get it to post my results as different series if that makes any sense.
SQL/PHP:
$params = array(&$_POST['query']);
$tsql1 = "SELECT TOP 10 Company_Names, Revenue_Value1, Revenue_Value2
FROM Database.test report
GROUP BY Company_Name
ORDER BY Revenue_Value1
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$getProducts = sqlsrv_query($conn, $tsql1, $params, $options);
if ($getProducts === false)
die( FormatErrors( sqlsrv_errors() ) );
while( $row = sqlsrv_fetch_array( $getProducts, SQLSRV_FETCH_ASSOC) )
{
$rows[] = $row;
}
echo json_encode($rows, JSON_NUMERIC_CHECK);
sqlsrv_free_stmt( $getProducts );?>
the sql prints out something like this
http://i.imgur.com/ww0kasV.png
And prints this chart:
http://i.imgur.com/rh8ICVH.png
Obviously, this is not how i want it to output..
I want it to output xAxis as Quarters, yAxis as Revenue_Value1 and Series-name as Company_Name.
i am currently using this to get my php data.
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("data.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Revenue',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
title: { text: 'Months'}
},
yAxis: {
title: {
text: 'Revenue'
},
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: json
});
});
});
});
</script>
data.php echoes:
{"Company_Names":"Company_Name","Revenue_Value1":45443,"Revenue_Value2":4654}
Of course i had to change some values because of some rules.. i hope that you can still see what i am trying to achieve.
EDIT:
$arr = array();
while( $row = sqlsrv_fetch_array( $getProducts, SQLSRV_FETCH_ASSOC) )
{
$name = $row['Distributor'];
$data = array($row['Value']);
$arr[] = array('name' => $name, 'data' => $data);
}
echo json_encode($arr, JSON_NUMERIC_CHECK);
This put my data out a way that HighCharts could read it

Your series should be in an array try something var j =[]; j.push(json); then do series: j

Related

Getting data from MySQL DB using PHP highstock

Of some reason I can't seem to get this to work with highstock range selector. The navigator and range selector is not displaying correct data groups. The default data grouping doesn't work. The data displays correct in highcharts:
As you can see, the data grouping doesn't work when clicking on the navigator zoom panel. Also the columns are not increasing
http://marialaustsen.com/htdocs/index.html
What am I missing?
Many thanks
PHP script PDO call
//Checking if a request has been made
if( isset( $_POST ) ) {
//Establishing connection and retrieving the data
try {
$con = new PDO( 'mysql:dbname=output;host=localhost', 'root', 'root' );
$results = $con->query( 'SELECT sent_ecards, date FROM details ORDER BY details.date' );
} catch ( PDOException $e ) {
echo 'Connection failed: ' . $e->getMessage();
}
if( isset( $results ) ) {
$data = [];
$categories = [];
$combined = [];
foreach( $results as $row ) {
array_push( $categories, $row['date'] );
array_push( $data, (int) $row['sent_ecards'] );
}
array_push( $combined, $data );
array_push( $combined, $categories );
header( 'Content-Type: application/json' );
echo json_encode( $combined );
}
}
Index file
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Send eCards</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="width: 100%; height: 800px;"></div>
<button data-action="retrieve_data">Retrieve New Data</button>
<script>
$(document).ready(function() {
//Sending request to the server on button click
$( '[data-action="retrieve_data"]' ).on( 'click', function( e ) {
e.preventDefault();
$.ajax({
url: 'retrieve-data.php',
type: 'POST',
//async: true,
//dataType: "json",
success: function( data ) {
console.log( data );
var axis = $( '#container' ).highcharts().get( 'datetime' ),
series = $( '#container' ).highcharts().get( 'rewards' );
axis.setCategories( data[1], false );
series.setData( data[0], false );
$( '#container' ).highcharts().redraw();
},
})
//Initializing basic chart configuration object
window.chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
type: 'column',
alignTicks: false
},
title: {
text: 'Send ecards'
},
rangeSelector: {
selected: 1
},
xAxis: {
type: 'datetime',
tickInterval:24 * 3600 * 1000 * 365,
labels: {
formatter: function () {
return Highcharts.dateFormat('%b \'%y', this.value);
}
},
title: {
text: 'Date'
},
id: 'datetime'
},
yAxis: {
title: {
text: 'Amount of ecards'
}
},
tooltip: {
valueSuffix: ' K',
useHTML: true,
crosshairs: true,
shared: true,
pointFormat: '<span style="color:{point.color}">\u25CF </span> <b>{point.series.name}: <b>{point.y}</b> ({point.percentage:.1f}%)<br/>',
formatter: function () {
return Highcharts.dateFormat('%A, %b %e, %Y', this.x);
},
},
series: [{
name: 'ecards',
id: 'rewards',
data: [],
pointInterval: 24*3600*1000,
pointStart: Date.UTC(2010,0,1)
}],
});
//$( '#container' ).(chartConfigOptions);
});
});
</script>
</body>
</html>
The data arrays from consol:
(2) [Array(1999), Array(1999)]
0
:
(1999) [843, 2, 544, 81, 45, 12, 454, 81, 45, 466, 3557, 578, 5, 3434, 65, 843, 3435, 544, 65, 843, 4324, 454, 323, 45, 3435, 544, 323, 45, 2, 546, 323, 45, 739, 3557, 342, 235, 2, 546, 342, 235, 565, 342, 235, 2432, 56, 3456, 2432, 56, 2432, 4543, 5, 3456, 2311, 5, 2839, 565, 5, 2839, 65, 4927, 2, 565, 7, 2, 544, 863, 29, 4324, 454, 5, 346, 466, 565, 5, 346, 2311, 454, 264, 68, 343, 546, 29, 4324, 454, 546, 29, 235, 565, 34, 346, 4324, 454, 34, 346, 739, 3557, 34, 346, 98, 454, …]
1
:
(1999) ["01/01/2010", "01/01/2011", "01/01/2012", "01/01/2013", "01/01/2014", "01/01/2015", "01/02/2010", "01/02/2011", "01/02/2012", "01/02/2013", "01/02/2014", "01/02/2015", "01/03/2010", "01/03/2011", "01/03/2012", "01/03/2013", "01/03/2014", "01/03/2015", "01/04/2010", "01/04/2011", "01/04/2012", "01/04/2013", "01/04/2014", "01/04/2015", "01/05/2010", "01/05/2011", "01/05/2012", "01/05/2013", "01/05/2014", "01/05/2015", "01/06/2010", "01/06/2011", "01/06/2012", "01/06/2013", "01/06/2014", "01/06/2015", "01/07/2010", "01/07/2011", "01/07/2012", "01/07/2013", "01/07/2014", "01/08/2010", "01/08/2011", "01/08/2012", "01/08/2013", "01/08/2014", "01/09/2010", "01/09/2011", "01/09/2012", "01/09/2013", "01/09/2014", "01/10/2010", "01/10/2011", "01/10/2012", "01/10/2013", "01/10/2014", "01/11/2010", "01/11/2011", "01/11/2012", "01/11/2013", "01/11/2014", "01/12/2010", "01/12/2011", "01/12/2012", "01/12/2013", "01/12/2014", "02/01/2010", "02/01/2011", "02/01/2012", "02/01/2013", "02/01/2014", "02/01/2015", "02/02/2010", "02/02/2011", "02/02/2012", "02/02/2013", "02/02/2014", "02/02/2015", "02/03/2010", "02/03/2011", "02/03/2012", "02/03/2013", "02/03/2014", "02/03/2015", "02/04/2010", "02/04/2011", "02/04/2012", "02/04/2013", "02/04/2014", "02/04/2015", "02/05/2010", "02/05/2011", "02/05/2012", "02/05/2013", "02/05/2014", "02/05/2015", "02/06/2010", "02/06/2011", "02/06/2012", "02/06/2013", …]

Highcharts with multiple dataLabels

I am using Highcharts to display transaction status for different months. The chart is displaying fine. To show the number of transactions for each month, I have placed a datalabel on top of each column. The code is given below:
$(function () {
$('#hc').highcharts({
chart: {
renderTo: 'container',
type: <?php echo $type ; ?>,
marginRight: 130,
marginBottom: 35
},
title: {
text: 'Transaction Status',
x: -20
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: <?php echo $monnth_series ?>
},
yAxis: {
title: {
text: 'Transactions'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
color: '#fff',
style: {fontWeight: 'bold'},
formatter: function() {return this.y},
y: -5,
rotation: 360
},
column: {
pointPadding: .2,
groupPadding: 0,
borderWidth: 1
}
}
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +': '+ this.y; +'</b>'
}
},
credits: { enabled: false },
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -6,
y: 90,
borderWidth: 0
},
series: <?php echo $series_data ?>
});
});
Now I want to place another datalabel on the body of the column which will show the type of the transaction.
If I try
formatter: function() {return this.series.name},
inside: true,
then the datalabel shows correctly but the datalabel on top of the column does not show up.
Any idea on how to do this ?

multiple charts in the same page php

I'm trying to draw two charts in the same page php using highcharts.But, just the first one was displayed.The $data1,$data2,$data3,$data4,$data5 are values returned by some functions.
page.php:
<div>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
<div id="containerone" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
<?php
include 'data.php';
$data1=data::amountUSD($res['id']);
$data2=data::amountEUR($res['id']);
$data3=data::Month($res['id']);
$data5=data::Totalminutejour($res['id']);
$data4=data::Day($res['id']);
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
$(function() {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'USD VS EUR'
},
xAxis: {
categories: [<?php echo join(',', $data3); ?>]
},
yAxis: {
title: {
text: 'Amount'
},
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: [ {
name: 'EUR',
data: [<?php echo join(',', $data2); ?>],
},
{
name: 'USD',
data: [<?php echo join(',', $data1); ?>],
},
]
});
});
$(function() {
var chartone = new Highcharts.Chart({
chart: {
renderTo: 'containerone',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Range Total Minutes every day',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: [<?php echo join(',', $data4); ?>]
},
yAxis: {
title: {
text: 'Total Minutes'
},
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: [{
name: 'TotalMinuteDay',
data: [<?php echo join(',', $data5); ?>],
},
]
});
});
</script>
</div>
That's what print_r returns:
print_r($data1); // Array ( [0] => 8.800000190734863 [1] => 20 )
print_r($data2); // Array ( [0] => 8.800000190734863 [1] => 2 )
print_r($data3); // Array ( [0] => 5 [1] => 5 [2] => 4 [3] => 4 )
print_r($data4); //Array ( [0] => a [1] => d )
print_r($data5); // Array ( [0] => 0.2 [1] => 0.2 )

Highcharts Column Chart Not Displaying Dynamic Values

Hi I need to create one dynamic column chart. But i am not able to put my values to the data field of value how can i do that
function getusercategorygraph()
{
$.getJSON('config/alumniusermodes.php',function(data){
// Create a new array
var finaldata = [];
var chart;
// Perform your operations
$.each(data, function( index, value ) {
// Create a new hash
var currentItem = {}
// Create the proper values in your hash
$.each(value, function( index, value ) {
currentItem[index] = value;
});
finaldata += currentItem;
});
var chart = new Highcharts.Chart({
chart: {
renderTo : 'user-count',
type: 'column',
},
title: {
text: 'Alumni Users By Category Analytics'
},
xAxis: {
color:'#0077CC',
//type: 'category',
categories: []
},
yAxis: {
title: {
text: 'Total Number of Alumni Members'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y} Members'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y} Members</b><br/>'
},
series: [{
name: "Alumni Type",
colorByPoint: true,
//data: [{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
//data: [{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
data : finaldata,
}],
});
});
}
But the graph doesnt show anything. Whats wrong in this code. Please help.
this is the result from api that i got
[{"name":"Standard","y":"52"},{"name":"Silver","y":"24"},{"name":"Gold","y":"20"},{"name":"Platinum","y":"6"}]
Thanks in Advance
To get you started, on line 18, change
finaldata += currentItem;
to
finaldata.push({
name: currentItem.name,
y: parseFloat(currentItem.y)
});
See JSFilddle.
Edit: Used suggestions by Sebastian in comments. Thanks!
Here is the working version keeping the highchart code inside $.getJSON callback function.
I added following PHP back-end code to get highchart sample data.
$data[] = array('name' => 'Standard', 'y'=> 52);
$data[] = array('name' => 'Silver', 'y'=> 24);
$data[] = array('name' => 'Gold', 'y'=> 20);
$data[] = array('name' => 'Platinum', 'y'=> 6);
echo json_encode($data);
exit;
This data is nothing but giving me data to use in highchart. Following is the javascript call to get it functional.
getusercategorygraph();
function getusercategorygraph()
{
$.getJSON('http://<mydomain>/getdata.php',function(data){
var chart = new Highcharts.Chart({
chart: {
renderTo : 'container',
type: 'column',
},
title: {
text: 'Alumni Users By Category Analytics'
},
xAxis: {
color:'#0077CC',
//type: 'category',
categories: []
},
yAxis: {
title: {
text: 'Total Number of Alumni Members'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y} Members'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat:'<span style="color:{point.color}">{point.name}</span>:<b>{point.y}Members</b><br/>'
},
series: [{
name: "Alumni Type",
colorByPoint: true,
data: data
}],
});
});
}

Highcharts chart with column and line using json

I am new to Highcharts and i already like it.
I have made some column charts using json, php en mysql (with given examples).
Now i want to make a chart with columns and a line using json.
Can anybody tell how i schould do that??
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("DataKwhDagCum.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'In (Enexis) vs Out (Zonnestroom)',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20','21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']
},
yAxis: {
title: {
text: 'Amount'
},
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: json
});
});
});
});
You can use two ways
use php and script in the same file: http://docs.highcharts.com/#preprocessing-data-from-a-database
return array as json by using json_encode() in php, and then use it in Highcharts.

Categories