Highcharts drilldown data from mysql - mysql

Im trying to use the drill down method for my chart similar to this: https://www.highcharts.com/demo/column-drilldown/sand-signika%5d%5b1%5d.
But I want to drilldown my data from YEARS,MONTHS,WEEKS & DAYS. How can I execute that? Heres my code:
$query = "SELECT sum(product_total) as total, YEAR(`date`) as year FROM confirm_order_product GROUP BY YEAR(date) ORDER BY date";
$result = $mysqli->query($query);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$salestotal[] = $row['total'];
$sdate[] = $row['year'];
}
$salesdate = json_encode($sdate, JSON_NUMERIC_CHECK);
$sales = json_encode($salestotal, JSON_NUMERIC_CHECK);
Container:
$(function() {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Sales Report'
},
xAxis: {
categories: <?php echo $salesdate; ?>
},
yAxis: {
title: {
text: 'Value'
},
},
tooltip: {
valuePrefix: '₱'
},
series: [{
name: 'Sales',
colorByPoint: true,
data:<?php echo $sales; ?>,
}],
});
});
This only displays per year.

Related

How To generate json format from model in codeigniter

I Have Database :
enter image description here
how to query mysql in codeigniter model so that it can output json data like this :
enter code here</script">
$.ajax({
url: '?grid=true&tahun=' + tahuncikarang,
method: "GET",
success: function(data) {
var obj = JSON.parse(data);
}
Highcharts.chart('cikarang', {
chart: {
type: 'bar'
},
title: {
text: 'Highcharts multi-series drilldown'
},
subtitle: {
text: 'The <em>allowPointDrilldown</em> option makes point clicks drill to the whole category'
},
xAxis: {
type: 'category'
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true
}
}
},
series: [{
name: '2010',
data: obj.tahun1
}, {
name: '2014',
data: obj.tahun2
}],
drilldown: {
allowPointDrilldown: false,
series: [{
id: 'republican-2010',
name: 'Republican 2010',
data: [
['East', 4],
['West', 2],
['North', 1],
['South', 4]
]
}, {
id: 'democrats-2010',
name: 'Republican 2010',
data: ''
}, ]
}
});
}
});
I try in model :
function index($tahuncikarang)
{
$this->db->select('nama AS nama, CONCAT(nama,"-", tahun) AS drilldown, sum(nilai) AS y');
$this->db->where('tahun=2010');
$this->db->group_by('nama')
->group_by('tahun');
$tahuna1 = $this->db->get(self::$table5);
$tahuna2 = array();
foreach ($tahuna1->result() as $row) {
array_push($tahuna2, $row);
}
$this->db->select('nama AS nama, CONCAT(nama,"-", tahun) AS drilldown, sum(nilai) AS y');
$this->db->where('tahun=2014');
$this->db->group_by('nama')
->group_by('tahun');
$tahunb1 = $this->db->get(self::$table5);
$tahunb2 = array();
foreach ($tahunb1->result() as $row) {
array_push($tahunb2, $row);
}
$result = array();
$result['tahun1'] = $tahuna2;
$result['tahun2'] = $tahunb2;
return json_encode($result, JSON_NUMERIC_CHECK);
}
I read your question just before.
If you could use this query, you maybe get good results.
Thank you
$qy = $this->db->query("select concat(lower(nama),'-',tahun) as id,concat(nama,'-',tahun) as name,group_concat(concat(zone,'-' ,nilai),',') as data group by nama, tahun")->result_array();
$result = array();
foreach($qy as $row) {
$temp = array(
"id"=>$row['id'],
"name"=>$row['name'],
"data"=>array()
);
$array = explode(',',$row['data']);
foreach($array as $el) {
$temp['data'][]=explode('-',$el);
}
$result[] = $temp;
}
echo json_encode($result);

How to fix SyntaxError: Unexpected token &

I am sending a php coded in accordance with the json_encode function to a plantilla.twig where I want to graph a pie chart type and the browser shows me the following error in console uncaught SyntaxError: Unexpected token & ¨ and I red the line following data: [[& quot; Intermediate 17.5 inches & quot;, 2220]]
Controller Class
public function tiempoXEtapaAction()
{
$em = $this->getDoctrine()->getManager();
$servicepozo = $this->get('service.pozo');
$pozoActual = $servicepozo->getPozoActual();
$idpozo = $servicepozo->getPozoActual()->getId();
$activityCollections = $em->getRepository('ActividadBundle:ActividadDiariaCollection')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$intervalos = $em->getRepository('IntervaloBundle:Intervalo')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$actividades = $em->getRepository('ActividadBundle:ActividadDiaria')->findBy(array('pozo' => $idpozo), array('id' => 'ASC'));
$tiempoXIntervalo = array();
foreach ($activityCollections as $activityCollection) //Dias
{
$fechaActCole = $activityCollection->getFecha();
foreach ($intervalos as $intervalo) //Intervalos
{
if ($intervalo->getFechaInicio() <= $fechaActCole && $intervalo->getFechaFinal() >= $fechaActCole) {
$temp = array();
$temp[] = $intervalo.'';
foreach ($actividades as $actividad) //Actividades
{
if ($actividad->getCollection()->getId() == $activityCollection->getId()) {
$duracion[] = $actividad->getDuracion();
}
}
$temp[] = array_sum($duracion);
}
}
$tiempoXIntervalo[] = $temp;
}
return array('tiempoXIntervalo'=> (json_encode($tiempoXIntervalo)));
Template.Twig
title: {
text: 'Distribución de tiempo por Intervalo'
},
xAxis: {
reversed: false,
title: {
enabled: true,
text: 'Dias'
},
labels: {
formatter: function () {
return this.value;
}
},
maxPadding: 0.05,
showLastLabel: true,
allowDecimals: false,
min:0,
},
yAxis: {
max:0,
startOnTick: false,
title: {
text: 'Profundidad [m]'
},
labels: {
formatter: function () {
return this.value;
}
},
lineWidth: 2,
},
legend: {
enabled: true
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y}h ({point.percentage:.1f}%)</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
data:{{tiempoXIntervalo}}
}]
});
});
</script>
You should check how to convert HTML entities
Also, there is an extra space in & quot;
It should be "
json_encode expects " so it should be ["Intermediate 17.5 inches",2220]
Thanks Fernando but your solution do not work for mi.
Apparently the problem was Twig autoescaping variables. I tried to use Twig's raw filter to skip autoescaping and it's work for mi. Here the solution
data: $.parseJSON('{{ tiempoXIntervalo | raw }}')

passsing data to https by JSON using JSONP

i had try many diffrent tutarials and examples from http://api.jquery.com/jQuery.getJSON/ and Post data to JsonP and saw many staffs about how to convert json data to jasonP but still i can not do it,is there any one could see how should i pass my data over https within my codes here which i am using highcharts to get data from my domain sql server which is in diffrent server than my webpages host.here is my codes:(i know which i should use ajax request but i dont know how in my case,if anyone know please HELP!) tnx.
getting data by getJASON over data.php which request from sql server to grab data:
var Options;
$(document).ready(function() {
Options = {
chart: {
renderTo: 'container2',
type: 'area',
borderColor: "#3366ff",
borderWidth:5,
zoomType : 'x'
},
title: {
text: 'Total Meeting_Logs Duration of Organization1 '
},
subtitle: {
text: ' '
},
credits:{
enabled:false
},
xAxis: {
categories: [],
labels: {
align: 'center',
x: -3,
y: 20,
//format data based on #datepicker which is html jquery ui date
//picker
formatter: function() {
return Highcharts.dateFormat('%l%p',
Date.parse(this.value +' UTC'));
}
}
},
yAxis: {
title: {
text: ''
}
},
tooltip: {
backgroundColor: '#FCFFC5',
borderColor: 'black',
borderRadius: 10,
borderWidth: 3
},
// Enable for both axes
tooltip: {
crosshairs: [true,true]
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
type: 'area',
name: '',
data: []
}]
}
// here i get my data from data.php within same server
$.getJSON("data.php", function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
});
//this function get user request for input time period and
//update in my domain
$(function() {
$( "#datepicker2" ).datepicker({
dateFormat: "yy-mm-dd",
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true,
onSelect: function(dateText, inst) {
$.getJSON("data.php?dateparam1="+dateText, function(json){
Options.xAxis.categories = json['category'];
Options.series[0].name = json['name'];
Options.series[0].data = json['data'];
chart = new Highcharts.Chart(Options);
});
}
});
});
data.php:
`
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moh1368_Mrs_Lemoine", $con);
if (isset($_GET["dateparam"])) {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '".$_GET["dateparam"]."%'");
} else {
$sql = mysql_query("SELECT timestamp_value, traffic_count FROM
foot_traffic WHERE timestamp_value LIKE '2013-02-01%'");
}
$result['name'] = 'Foot Traffic Count';
while($r = mysql_fetch_array($sql)) {
$datetime = $r['timestamp_value'];
$result['category'][] = $datetime;
$result['data'][] = $r['traffic_count'];
}
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>`

HighCharts issues in Dual axes, line and column charts

I am trying to generate Dual axes, line and column charts of highcharts .I have tried stackoverflows sugesstions but i couldn't find proper solution.I have the data formatted properly but yet the chart is not generate shows blank.I want this type of [link] http://jsfiddle.net/sunman/dwyNz/8/ .In spline line I want to show 'bsp values' and in column I want to show facilities_total. So below i show my code for this graph.I also pointed my error in index.php.
Here is my Index.php
$(function () {
$('#container').highcharts({
chart: {
zoomType: 'xy'
},
title: {
text: 'Project faclityv Rating'
},
subtitle: {
text: 'testing'
},
xAxis: [{
categories: []
}],
yAxis: [{ // Primary yAxis
labels: {
// format: '{value} Rs.',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Bsp Cost',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, { // Secondary yAxis
title: {
text: 'facility rating',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
//format: '{value} out of 100',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 100,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
series: [{
name: 'Facility Rating',
type: 'column',
yAxis: 1,
data: [],
tooltip: {
valueSuffix: ' out of 100'
}
}, {
name: 'Bsp Cost',
type: 'spline',
data: [],
tooltip: {
valueSuffix: 'Rs.'
}
}]
});
$.getJSON("combochart.php", function(json) {
options.xAxis.categories = json[0]['data']; /*error here: ReferenceError: options is not defined */
options.series[0] = json[1];
options.series[1] = json[2];
chart = new Highcharts.Chart(options);
});
});
Here is my combochart.php
$query1 = mysql_query("SELECT projects_detail.Project_name,superfac_rating.faci_total
FROM projects_detail LEFT OUTER JOIN superfac_rating
ON projects_detail.project_id= superfac_rating.project_id ");
$category = array();
$category['name'] = 'Project';
while($row1 = mysql_fetch_array($query1)) {
$category['data'][] = $row1['Project_name'];
$series1['data'][] = $row1['faci_total'];
}
$query2 = mysql_query("SELECT projects_detail.Project_name,superfac_rating.faci_total
FROM projects_detail LEFT OUTER JOIN superfac_rating
ON projects_detail.project_id= superfac_rating.project_id
LEFT OUTER JOIN cost ON gsuperfac_rating.project_id=cost.project_id ");
$series1 = array();
$series1['name'] = 'Project Name';
$series2 = array();
$series2['name'] = 'BSP VALUES';
while($row2 = mysql_fetch_array($query2)) {
$series1['data'][] = $row2['faci_total'];
$series2['data'][] = $row2['bsp'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series1);
array_push($result,$series2);
print json_encode($result, JSON_NUMERIC_CHECK);
I think i have problem in json code thats why i can't fetch data for graph.i checked in my console no errors.but i debug this code and json result shows me(json o/p writes in jsfiddle) but graph not appear in browser. i am explained in jsfiddle[link] jsfiddle.net/sunman/rDYvt/9 please check this. give me solution where i am wrong.So please help me and resolve my query.
Inside your $.getJSON("combochart.php", function(json) you need to setData like this
theChart.xAxis[0].setCategories(json[0]['data']);
theChart.series[0].setData(json[1]['data'], false);
theChart.series[1].setData(json[2]['data'], true);
Ok, it's working now...
Paste this in a JSFiddle to see it working...
$(document).ready(function() {
var json= '[{"name":"Project","data":["Green View","Grand","Arete","Canary Greens","Terra","Beethovens","Ninex City","South Park","Callidora","Lotus","Coban","NCR Green","Kocoon","Estella","NCR One"]},{"name":"Facilities Rating","data":[45,55,55,55,55,55,55,55,55,55,55,55,55,55,55]},{"name":"BSP VALUES","data":[97500,55745,16400,98700,38600,12090,94700,11400,12450,89500,86725,88335,54200,18200,30400]}]'
var jsobj = JSON.parse(json)
var firstSeriesData = [];
var secondSeriesData = [];
jsobj[1].data.forEach(function(seriesOneData){
firstSeriesData.push(seriesOneData);
})
jsobj[2].data.forEach(function(seriesTwoData){
secondSeriesData.push(seriesTwoData);
})
$('#container').highcharts({
chart: {
zoomType: 'xy',
type: 'column',
marginRight: 130,
marginBottom: 50
},
title: {
text: 'Top 12 Projects Facilities Rating and BSP Costs ',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: jsobj[0].data
},
yAxis: {
min: 0,
title: {
text: 'Facilities Rating'
},
plotLines: [{
value: 0,
width:1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
plotOptions:{
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color:'white'
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
borderWidth: 0,
x: -10,
y:110
},
series: [ {
name:'Facilities Rating',
data:firstSeriesData,
id:'dataseries'
},{
name:'BSP',
type:'spline',
data:secondSeriesData
}]
})
});
A couple comments.. your JSON had an unidentified character in it. This is what I got from pasting your JSON string.
Notice that red dot in the middle of the JSON.
Also, make sure you load highcharts modules in this order...
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
And lastly, you have two series in there, but one of them has values below 100 and the other one has values over 100k. So the first series is not gonna show as it almost 0 compared to the second. You'll have to do something about that.
In your function $.getJSON("combochart.php", function(json) you need to explicitly define what options you want. You are also not acutally setting any data. I am assuming that json[0]['data'] is a list of categories like ['Cat1', 'Cat2',...] and that json[1] and json[2] contain the data like [val1, val2, ...]. If so you need to do something like this:
$.getJSON("combochart.php", function(json) {
var theChart = $('#container').highcharts();
theChart.xAxis[0].setCategories(json[0]['data']); /*error here: ReferenceError: options is not defined */
theChart.series[0].setData(json[1]);
theChart.series[1].setData(json[2]);
//chart = new Highcharts.Chart(options);
});
});

Flexigrid in zend

i have a page post2.php which prints the json array like
{
page: 1,
total: 239,
rows: [{
id: '239',
cell: ['239', 'ZW', 'ZIMBABWE', 'Zimbabwe', 'ZWE', '716']
},
{
id: '238',
cell: ['238', 'ZM', 'ZAMBIA', 'Zambia', 'ZMB', '894']
},
{
id: '237',
cell: ['237', 'YE', 'YEMEN', 'Yemen', 'YEM', '887']
},
{
id: '236',
cell: ['236', 'EH', 'WESTERN SAHARA', 'Western Sahara', 'ESH', '732']
},
{
id: '235',
cell: ['235', 'WF', 'WALLIS AND FUTUNA', 'Wallis and Futuna', 'WLF', '876']
},
{
id: '234',
cell: ['234', 'VI', 'VIRGIN ISLANDS, U.S.', 'Virgin Islands, U.s.', 'VIR', '850']
},
{
id: '233',
cell: ['233', 'VG', 'VIRGIN ISLANDS, BRITISH', 'Virgin Islands, British', 'VGB', '92']
},
{
id: '232',
cell: ['232', 'VN', 'VIET NAM', 'Viet Nam', 'VNM', '704']
},
{
id: '231',
cell: ['231', 'VE', 'VENEZUELA', 'Venezuela', 'VEN', '862']
},
{
id: '230',
cell: ['230', 'VU', 'VANUATU', 'Vanuatu', 'VUT', '548']
}
]
}
and in zend views i am trying to do like
$(document).ready(function() {
$("#flex1").flexigrid({
url: '/public/**post2.ph**p',
dataType: 'json',
colModel: [{
display: 'ID',
name: 'id',
width: 40,
sortable: true,
align: 'center'
},
{
display: 'ISO',
name: 'iso',
width: 40,
sortable: true,
align: 'center'
},
{
display: 'Name',
name: 'name',
width: 180,
sortable: true,
align: 'left'
},
{
display: 'Printable Name',
name: 'printable_name',
width: 120,
sortable: true,
align: 'left'
},
{
display: 'ISO3',
name: 'iso3',
width: 130,
sortable: true,
align: 'left',
hide: true
},
{
display: 'Number Code',
name: 'numcode',
width: 80,
sortable: true,
align: 'right'
}
],
buttons: [{
name: 'Add',
bclass: 'add',
onpress: test
},
{
name: 'Delete',
bclass: 'delete',
onpress: test
},
{
separator: true
},
{
name: 'A',
onpress: sortAlpha
},
],
searchitems: [{
display: 'ISO',
name: 'iso'
},
{
display: 'Name',
name: 'name',
isdefault: true
}
],
sortname: "id"
sortorder: "asc",
usepager: true,
title: 'Countries',
useRp: true,
rp: 10,
showTableToggleBtn: true,
width: 700,
height: 255
});
});
this prints the flexigrid layout well.. but never gets the data.it keeps telling processing.
is there some problem in the json array or in the flexigrid calling... or in zend with json.
any suggestions to try out for this problem?
i tried out like this also
$.post("/public/server_processing1.php",{},function(data){
alert('hai');
alert(data);
}, "json");
and its not even alerting hai ..
full post2.php code is like this
<?
error_reporting(1);
function runSQL($rsql) {
$hostname = "localhost";
$username = "root";
$password = "root";
$dbname = "hms1";
$connect = mysql_connect($hostname,$username,$password) or die ("Error: could not connect to database");
$db = mysql_select_db($dbname);
$result = mysql_query($rsql) or die ('test');
return $result;
mysql_close($connect);
}
function countRec($fname,$tname,$where) {
$sql = "SELECT count($fname) FROM $tname $where";
$result = runSQL($sql);
while ($row = mysql_fetch_array($result)) {
return $row[0];
}
}
$page = $_POST['page'];
$rp = $_POST['rp'];
$sortname = $_POST['sortname'];
$sortorder = $_POST['sortorder'];
if (!$sortname) $sortname = 'pa_name';
if (!$sortorder) $sortorder = 'desc';
if($_POST['query']!=''){
$where = "WHERE `".$_POST['qtype']."` LIKE '%".$_POST['query']."%' ";
} else {
$where ='';
}
if($_POST['letter_pressed']!=''){
$where = "WHERE `".$_POST['qtype']."` LIKE '".$_POST['letter_pressed']."%' ";
}
if($_POST['letter_pressed']=='#'){
$where = "WHERE `".$_POST['qtype']."` REGEXP '[[:digit:]]' ";
}
$sort = "ORDER BY $sortname $sortorder";
if (!$page) $page = 1;
if (!$rp) $rp = 10;
$start = (($page-1) * $rp);
$limit = "LIMIT $start, $rp";
$sql = "SELECT pa_id,pa_name,pa_pd_patient_id,pa_name FROM patient_appointment $where $sort $limit";
$result = runSQL($sql);
$total = countRec('pa_id','patient_appointment',$where);
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
header("Content-type: text/x-json");
$json = "";
$json .= "{\n";
$json .= "page: $page,\n";
$json .= "total: $total,\n";
$json .= "rows: [";
$rc = false;
while ($row = mysql_fetch_array($result)) {
if ($rc) $json .= ",";
$json .= "\n{";
/*$json .= "cell:['".$row['pa_name']."'";
$json .= ",'".addslashes($row['time'])."'";
$json .= ",'".addslashes($row['pa_um_id'])."'";
$json .= ",'".addslashes($row['pa_pd_patient_id'])."']";*/
$json .= "id:'".$row['pa_id']."',";
$json .= "cell:['".$row['pa_id']."','".$row['pa_name']."'";
$json .= ",'".addslashes($row['pa_pd_patient_id'])."']";
$json .= "}";
$rc = true;
}
$json .= "]\n";
$json .= "}";
echo $json;
?>
I'm guessing you're using IE browser. If so IE does not like <div id="flex1"></div> container. Change it to <table id="flex1"></table> and all should work.