Creating Pie chart in High Chart - php

I'm having a table in MySQL with the following data
Buy_client Amount
ABC 6597
XYZ 4479
PQR 2075
qqq 1706
ttt 1030
Other 450
I want to show the following data in a Pie Chart in High Charts. Someone please help me with this. I'm new to both PHP and HighCharts
Question 1: I need to Create a Pie chart from this data
Question 2: I'm using HighCharts for this. Someone please help me to do this in HighCharts
I have used the following code to do this but it doesn't show the info in a pie chart but just display the data in the web browser
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("offlinesurv", $con);
$my_data = mysql_query("SELECT * FROM top_buy_clients");
while($row = mysql_fetch_array($my_data)) {
echo $row['buy_client'] . "\t" . $row['qty']. "\n";
}
?>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2010'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: 'green',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [ <?php echo $row; ?>]
}]
});
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>

In your php...where you make the query to the database....in the while loop, you need to construct and string and in the end of the loop the string should looks like:
$my_data = "['ABC', 6597],
['XYZ', 4479],
['PQR', 2075],
['qqq', 1706],
['ttt', 1030],
['Others', 450] ";
Then in your javascript file, you should have a line like this
series: [{
type: 'pie',
name: 'Pie Data',
data: [
<?php echo $my_data; ?>
]
}]
It's very simple.
Saludos.

Related

Data not loading in HighChart from MYSQL

I have recently started working on Highchart. I dont have indepth knowledge. But I am still trying my level best. I have tried few codes, but I didn't get any results. The browser console is not loading anything and it is showing blank. Can you please help me in pointing out what to do next. I tried my level best. Please me out.
Here is my code:
Database Coding: php.data
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","root","demo") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from project_requests";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//close the db connection
mysqli_close($connection);
?>
index.php
<!DOCTYPE HTML>
<?php
include_once 'data.php';
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares January, 2015 to May, 2015'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Brands',
colorByPoint: true,
data: [
<?php
//$sql = mysqli_query("select * from project_requests")
while($res=mysql_fetch_array($sql)){
?>
['<?php echo $res['month']; ?>', 45.0],
<?php
}
?>
]
}]
});
});
</script>
</head>
<body>
<script src=
"https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
</body>
</html>
MY sql: Database Snapshot
Schema:: Demo Table:: project_requests

how to show data for single day in graph using php mysql

I am using HighCharts and im showing temperature on the graph. I was thinking that is it possible to show data for a single day only or 1 week or over a month using highchart graph. Right now I get all the data which is from the 1st record to the latest one from MySQL DB . Here is the code .
this is data.php -
<?php
$con = mysql_connect("192.168.100.107:3306","root","hannan786");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("pi", $con);
$sth = mysql_query("SELECT * FROM temperature ");
$rows = array();
$rows['Temperature'] = 'temperature';
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['temperature'];
}
$result = array();
array_push($result,$rows);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
And this is the code for the main Page where the graph data is displayed -
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Refresh" Content="5">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Temperature</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<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: 'Temperature',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: ['Temperature']
},
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
});
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Right Now I get this as output -
You can use the method setExtremes() of the Highcharts Api. You only have to provide min and max value, that in your case consists of the same Date Object, I think.
This is a fiddle as an example on how to use it.
chart.xAxis[0].setExtremes(
Date.UTC(2007, 0, 1),
Date.UTC(2007, 11, 31)
);
Docs are here: http://api.highcharts.com/highstock#Axis.setExtremes

Fetching data from mysql database in high charts

I am trying to pull data from mysql and display on highchart bar graph, but I am not sure where my code is incorrect. The result is a blank page.
The code could not be wrong as I have taken it from the index.html file that highchart provides, but it doesn't work for some reason. Could anyone check and let me knpw where I am making any error?
<!DOCTYPE HTML><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="js/highcharts.js"></script>
<script src="js/modules/exporting.js"></script>
<?php
$host="localhost";
$username="root";
$password="";
$db="isat";
// Create connection
$con = mysqli_connect($host,$username,$password,$db) or die("Error Message: <br>". mysqli_error($con));
$data=array();
$query= "SELECT standard FROM domainlist";
$result=mysqli_query($con,$query);
while($row=mysqli_fetch_assoc($result)){
$data[]=$row['standard'];
}
?>
<script type="text/javascript">
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
xAxis: {
categories: [<?php echo join($data, ','); ?>]
},
series: [{
data: [],
pointStart: 0,
pointInterval
}]
}); $(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Compliance'
},
yAxis: {
min: 0,
title: {
text: 'Total fruit consumption'
}
},
legend: {
reversed: true
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
});}); </script></head>
<body><div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div></body></html>

what should i write in series of highcharts

I want to use my database data in series
my table “mob” is something like this :
![my table named "mob"][1]
Icost data in not real
And my code is like this :
<?php
include '../../class/jdf.php';
require_once "../../db.php";
$db = new db();
$query_time = "SELECT DISTINCT iDate FROM mob WHERE 1 ";
$datashow = $db->get_arr($query_time);
$time = array();
foreach ($datashow as $key => $row) {
$format = ' Y/m/d ';
$time[] = jdate($format, $row['iDate']);
}
$query_cost = "SELECT * FROM mob WHERE 1 ";
$data = $db->get_arr($query_cost);
$datamin = $db->get_field('mob','MIN(iCost)','1');
$datamin = $datamin -100;
$datamax = $db->get_field('mob','MAX(iCost)','1');
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script src="../../js/jquery-1.9.1.min.js"></script>
<script src="../../js/highcharts.js"></script>
<style type="text/css">
</style>
<script type="text/javascript">
Highcharts.setOptions({
lang: {
numericSymbols: null
},
});
$(function() {
$('#container').highcharts({
chart:
{
type: 'column'
},
title: {
text: 'my chart '
},
subtitle: {
text: 'mob'
},
xAxis: {
categories: [
<?php
foreach ($time as $value) {
echo "'" . $value . "',";
}
?>
]
},
yAxis: {
min :<?php echo $datamin ?>,
max :<?php echo $datamax ?>,
title: {
text: 'cost'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: []
});
});
</script>
</head>
<body>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>
What should I write in series to have a chart like this
![my chart sample is like this][2]
// [1]: http://i.stack.imgur.com/WBJm5.jpg
// [2]: http://i.stack.imgur.com/DYZjm.jpg
Help me please .
Thank you
In your php, prepare correct array (according to avascript structure) and use json_encode(). In javasctrip call $.getJSON(), get data and use in the highcharts.
More information about preprocessing data, here

creating flot chart style

im trying to style my flot charts similar to this:
this is my current chart:
here is my chart code,
<?php
include('Includes/connect.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cs" lang="cs">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf8"/>
<title>Index</title>
<script src="Includes/jquery-1.8.3.js"></script>
<script src="Includes/jquery.flot.js"></script>
<script src="Includes/jquery.flot.time.js"></script>
</head>
<?php
// Main query to pull data from 'tests' table
$sql = "SELECT UNIX_TIMESTAMP(`date`)*1000 AS unixDate,`date`, `test1`, `test2`, `test3`, `test4`, `test5`, `test6`, `test7`, `test8`, `test9`, `test10`, `test11`, `test12`, `test13`, `test14` FROM `tests` WHERE member_id = '1' ORDER by `date` ASC";
$result = mysql_query($sql) or die ("no query");
// Dataset1
while($row = mysql_fetch_assoc( $result )) {
$dataset1[] = array( $row['unixDate'], sprintf( "%.3f", $row['test1'] ));}
?>
<div id="chart1" style="width:700px;height:300px;"></div>
<script type="text/javascript">
//Chart1
var chart1Options = {
xaxis: {mode: "time", timeformat: "%Y-%m-%d"},
lines: { show: true, color: "#fff" },
points: { show: true },
grid: {
backgroundColor: { colors: ["#4ca8fa", "#2887da"] },
bordercolor: "#fff",
borderwidth: "60",
hoverable: true }
};
var dataset1 = { data: <?php echo json_encode($dataset1); ?>,};
$.plot($("#chart1"), [ dataset1 ], chart1Options);
</script>
</body>
</html>
can anyone help me out please? similar colours and also i cant seem to get hover data showing up either
thanks.
This should get you close to the appearance you want.
HTML:
<div id="placeholder" style="width:400px;height:300px;background-color: #6EB5F0"></div>
JS:
$(function () {
var plot = $.plot($("#placeholder"),[
{ data: [[0,0],[1,1],[2,4],[3,3],[4,5],[5,7],[6,9],[7,10],[8,8],[9,12]], color: 'white'}
], {
series: {
lines: { show: true, fill: true, fillColor: 'rgba(143, 198, 242, 0.7)' },
points: { show: true}
},
grid: { color: 'transparent' },
xaxis: {
color: 'white',
font: { color: 'white', family: 'sans-serif', size: 11}
},
yaxis: {
color: 'white',
font: { color: 'white', family: 'sans-serif', size: 11}
}
});
});
Result:
Fiddle here.
As far as your hover tooltips not working, there's a great example here. Follow that and if you still can't get it working, update your question with specifics and a minimal code sample that demonstrates the problem.

Categories