How to loop the data[] series with php and mysql - php

Here is my table structure.
I am using highcharts
Here is my code:
$(function () {
$('#container_journal').highcharts({
xAxis: {
categories: [
'1995', '1996', '1997', '1988'
]
},
yAxis: {
title: {
text: 'Citations'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: ''
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'A + U-Architecture and Urbanism',
data: [<?php
$test_q = mysql_query("SELECT jour_id, journal, citations, year FROM journ_graph WHERE jour_id = '1'");
while($row_q = mysql_fetch_array($test_q)){
$year_q = $row_q['year'];
$citations_q = $row_q['citations'];
echo $citations_q.',';
}
?>]
},{
name: 'AACE International. Transactions of the Annual Meeting',
data: [
<?php
$test_q = mysql_query("SELECT jour_id, journal, citations, year FROM journ_graph WHERE jour_id = '2'");
while($row_q = mysql_fetch_array($test_q)){
$year_q = $row_q['year'];
$citations_q = $row_q['citations'];
echo $citations_q.',';
}
?>]
},{
name: 'AACL Bioflux',
data: [
<?php
$test_q = mysql_query("SELECT jour_id, journal, citations, year FROM journ_graph WHERE jour_id = '3'");
while($row_q = mysql_fetch_array($test_q)){
$year_q = $row_q['year'];
$citations_q = $row_q['citations'];
echo $citations_q.',';
}
?>]
}
?>]
]
});
});
Here im entering manually the id. in where clause(refer code), the graph is showing.
Look Below:
SELECT jour_id, journal, citations, year FROM journ_graph WHERE jour_id = '3'
In the above statement im entering the id manually, but i need it to come from the first table, jour_id.
I tried that too but its not working.
series: [
<?php
$query_jour = mysql_query("SELECT jour_id, journal, citations, year FROM journ_graph");
$query_journ_count = mysql_num_rows($query_jour);
while($row_journ = mysql_fetch_array($query_jour)){
$jour_id = $row_journ['jour_id'];
?>
{
data: [<?php
$test_q = mysql_query("SELECT jour_id, journal, citations, year FROM journ_graph WHERE jour_id = '$jour_id'");
while($row_q = mysql_fetch_array($test_q)){
$year_q = $row_q['year'];
$citations_q = $row_q['citations'];
echo $citations_q.',';
}
?>]
}
<?php
}?>
I have used two while loops but eventhough its not working. Please tell me where I am going wrong. Please help.

I advice you to run one query to database, prepare array which will contain three series, then you json_encode() in PHP and get data via AJAX in javascript. It will be more clearful.

Related

Highcharts live data, json ajax

My head is going to blow.
livedata.php loads json when page open.
live.php add point to graph.
From livedata.php i got output like this:
[["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37]]
live.php output - only last row, looks like
["Date.UTC('.2016, 07-1, 29, 15, 40.')", 44]
I've got chart, live addPoint working, but no date on x-axis. What i do wrong?
JS
var chart;
function requestData() {
$.ajax({
url: 'live.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 120; // shift if the series is
chart.series[0].addPoint(eval(point));
setTimeout(requestData, 10000);
},
cache: false
});
}
$(function () {
$.ajax({
url: 'livedata.php',
success: function(point) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'areaspline',
events: {
load: requestData
}
},
title: {
text: 'Revenue vs. Overhead',
},
subtitle: {
text: '',
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
series: [{
name: 'Random data',
data: eval(point )
}]
});
},
});
});
live.php
global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata order by id desc limit 1');
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = "Date.UTC('.$date_raw.')";
$ar = array($date_complete, $row[humidity]);
echo json_encode($ar, JSON_NUMERIC_CHECK);
livedata.php
global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata');
$result = $stmt->fetchAll();
foreach ($result as $row) {
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = 'Date.UTC('.$date_raw.')';
$hum_for_chart[] = [$date_complete, $row[humidity]];
}
echo json_encode($hum_for_chart, JSON_NUMERIC_CHECK);
Chart:
Chart
I think its problem of your data try to make string like,
live.php
....
$date_complete = "Date.UTC('.$date_raw.')";
$ar = "[".$date_complete.",". $row[humidity]."]";
echo json_encode($ar);
livedata.php
....
foreach ($result as $row) {
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = 'Date.UTC('.$date_raw.')';
$hum_for_chart[] = "[".$date_complete.",". $row[humidity]."]";
}
....
You can refer highcharts-data-series-issue-with-ajax-json-and-php
i've got it! 2 days of mind blowing ))))
Thanks to Rohan Kumar for link.
I made changes from date.utc to unix timestamp.
$datetimeUTC = ((strtotime($row[dataa])+ 10800) * 1000);
$data[] = [$datetimeUTC, $row[humidity]];
echo json_encode($data);
10800 - that is +3 hours (Moscow timezone)
The output is
[[1469718529000,37],[1469718529000,37],[1469718530000,37],[1469718531000,37]]
And that's it, date axis started working!

How to display data in HIGHCHART from mysql database using datepicker?

have a problem when i choose the start date and end date in datepicker to display the data in highchart, the data in highchart is display alll data..so plaese some body to fix it. thank u
this's my source code
<script>
function dialogbx(){
myDialogBox('9');
}window.addEventListener("load",dialogbx);
</script>
<script type="text/javascript">
var chart1; // globally available
$(document).ready(function() {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: ''
},
subtitle: {
text: 'Type Grafik : Column'
},
xAxis: {
categories: [
<?php
$sql2 = "SELECT * FROM pinjaman WHERE $filterPeriode GROUP BY tgl_pinjam ";
$query2 = mysql_query( $sql2 ) or die(mysql_error());
while($ret2=mysql_fetch_array($query2)){
$tahun = $ret2['tgl_pinjam']; ?>
'Tanggal <?php echo $tahun; ?>',
<?php } ?>
] ,
},
yAxis: {
title: {
text: 'Jumlah Pinjaman (Rupiah) '
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [
<?php
include('../library/inc.connection.php');
$query1=mysql_query("select kd_jenis from pinjaman where $filterPeriode && level ='1' group by kd_jenis");
while($array1=mysql_fetch_array($query1)){
$kdjenis = $array1['kd_jenis'];
?>
{
name: '<?php echo $kdjenis; ?>',
data: [<?php $query3 = mysql_query("select * from pinjaman WHERE $filterPeriode && level ='1' group by tgl_pinjam ");
while($array3 = mysql_fetch_array($query3)){
$query4 = mysql_query("select kd_jenis,SUM(jumlah_pinjam) from pinjaman where kd_jenis='$kdjenis' &&
$filterPeriode && level ='1' group by kd_jenis ");
while( $data = mysql_fetch_array( $query4 ) ){
$jumlah = $data['SUM(jumlah_pinjam)'];
}
echo $jumlah.",";
} ?>]
},
<?php } ?>
]
});
});
</script>

Getting Data from Database for HighCHarts

I am developing a tool which has a statistic page on which I am using HighCharts, I am using the basic line chart, Now to populate this chart I need some data. The data comes from my DB.
I got a query which extracts a list of users assigned to a particular 'Manager', Now I want each name to appear a s different line.
But What happens is that all names appear under one line........
My code:
<?php
session_start();
class ManagerStats{
public function con()
{
require_once('connect.php');
$DB = new dbConnect();
return $DB->connect();
}
public function DontEvenKnow(){
if($_SESSION['user'] == 'manager1#gmail.com'){
$sql = "SELECT user_id, first_name FROM tbl_user WHERE user_team='bob'";
$query = mysqli_query($this->con(), $sql);
if($query){
foreach($query as $v){
echo $v;
}
}
}elseif($_SESSION['user'] == 'manager2#gmail.com'){
//$sql = "SELECT user_id FROM tbl_user WHERE user_team='oli'";
}
}
}
?>
<script>
$(function () {
$('#home_manager').highcharts({
title: {
text: '',
x: -20 //center
},
xAxis: {
categories: ['04/19', '04/20', '04/21', '04/22', '04/23', '04/24']
},
yAxis: {
title: {
text: 'Emails Sent'
},
plotLines: [
{
value: 0,
width: 1,
color: '#808080'
}
]
},
tooltip: {
valueSuffix: ''
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [
{
name: '<?php $oko = new ManagerStats(); $oko->DontEvenKnow(); ?>',
data: [38, 78, 12, 80, 75]
},
{
name: 'Helena',
data: [23, 34, 55, 67, 34]
},
{
name: 'Martin',
data: [34, 35, 55, 69, 67]
},
{
name: 'Marta',
data: [43, 64, 75, 57, 64]
},
{
name: 'Samuel',
data: [63, 64, 75, 87, 44]
},
{
name: 'Carter',
data: [43, 54, 55, 67, 84]
}
]
});
});
</script>
In your function :
$data = "";
$data_for_user = "[43, 54, 55, 67, 84]";
//For each user you need to get data from database,
//but don't do a query inside a loop because it kills perfomance
foreach($query as $v){
$data .= " {
name: '".$v["first_name" ]."',
data: ".$data_for_user."
}, ";
}
echo $data;
then in series
series: [<?php $oko = new ManagerStats(); $oko->DontEvenKnow(); ?>]
This will do a new line on highcharts foreach user that you have
UPDATE: was missing one of the quotes on the array that might be why it wasn't working for the person if they just copied it.
UPDATE:
Getting data for more users for highcharts
You need a query with users and all his values that have to be in the graph:
$query = "SELECT t.user_id, t.first_name, group_concat( v.values ) as data_for_user
FROM tbl_user t,tbl_values v
WHERE t.user_id = v.user_id
GROUP by t.user_id";
Group concat get the values for user separated by comma the way you need for highcharts.
Remember that group_concat have a lenght limit of 1024 but you can change it with this before your query.
'SET GLOBAL group_concat_max_len=15000'
And data for highcharts
$data = "";
foreach($query as $v){
$data .= " {
name: '".$v["first_name" ]."',
data: [".$v["data_for_user"]."]
}, ";
}
Try adding a line break after you echo out the variable. Something like this:
echo $v . "<br />";
That should create a new line after each user.

While loop not working in the series data highcharts - php

This is my Table structure
Here is my code: <br/>
<?php
$result_journ = mysql_query("SELECT jour_id, journal FROM journals");
$count_result = mysql_num_rows($result_journ);
while ($row_sd = mysql_fetch_array($result_journ)) {
$data_sd = $row_sd['jour_id'];
$namee= $row_sd['journal'];
?>
<script type="text/javascript">
$(function () {
$('#container_journal').highcharts({
xAxis: {
categories: [<?php
$test_q = mysql_query("SELECT jour_id, year FROM journ_graph WHERE jour_id = '$data_sd'");
while($row_q = mysql_fetch_array($test_q)){
$year_q = $row_q['year'];
echo $year_q.',';
}?>
]
},
yAxis: {
title: {
text: 'Citations'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: '<?php echo $namee; ?>',
data: [<?php
$sql= "SELECT `citations`, `jour_id` FROM `journ_graph` WHERE `jour_id` = '$data_sd'";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
echo $cita = $row['citations'].',';
?>]
}]
});
});
</script>
<?php
}
?>
The Result:
This is the result I am getting.
The expected Result:
The while loop is getting only one row. What would be the problem? Please help.
The while loop is getting only one row. What would be the problem? Please help.
Update Result:
Checkbox select
You are reinitializing the highcharts on each iteration of first while. Try the following code:
<?php
$result_journ = mysql_query("SELECT jour_id, journal FROM journals");
$count_result = mysql_num_rows($result_journ);
$categories = "";
$cita = array();
$count=0;
while ($row_sd = mysql_fetch_array($result_journ))
{
$data_sd = $row_sd['jour_id'];
$cita[$count]['name'] = $row_sd['journal'];
$test_q = mysql_query("SELECT jour_id, year FROM journ_graph WHERE jour_id = '$data_sd'");
while ($row_q = mysql_fetch_array($test_q))
{
$year_q = $row_q['year'];
$categories .= $year_q . ',';
}
$sql = "SELECT `citations`, `jour_id` FROM `journ_graph` WHERE `jour_id` = '$data_sd'";
$result = mysql_query($sql);
// I have added this while block thinking that you might have more than one rows
while ($row = mysql_fetch_array($result))
{
$cita[$count]['data'][] = $row['citations'];
}
$count++;
}
?>
<script type="text/javascript">
$(function () {
$('#container_journal').highcharts({
xAxis: {
categories: [<?= $categories ?>]
},
yAxis: {
title: {
text: 'Citations'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: <?= json_encode($cita, JSON_NUMERIC_CHECK) ?>
});
});
</script>

Issues Rendering Highcharts - Populating through PHP/MySQL

I'm hoping someone can help me here, I've been looking at highcharts as a way of graphing my dynamic data from my sql db....What I've come up with so far is below, it's strange, it seems correct, the data is correct, however, I can't get my chart to render, now I've tried viewing the chart through both Chrome and IE but with no results, can anyone see where I might've gone wrong, or where there is an error...my data is passing into the JS arrays, so there's an issue with the rendering end... Any help would be much appreciated. I have closed off my html tag, but for some reason it isn't displaying in this post...if anyone has any suggestions I would be happy to hear them!
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src='highcharts.js' type='text/javascript'> </script>
<script src='exporting.js' type='text/javascript'> </script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"type="text/javascript"></script>
</head>
<body>
<?php
include "connect_db.php";
$SQL1 = "SELECT review.reviewForum AS reviewForum,
COUNT(CASE WHEN mom.result = 'Approved' THEN 'yes' ELSE NULL END) AS Approved,
COUNT(CASE WHEN mom.result = 'NOT Approved' THEN 'yes' ELSE NULL END) AS Not_Approved,
COUNT(CASE WHEN mom.result = 'Cancelled' THEN 'yes' ELSE NULL END) AS Cancelled
FROM review INNER JOIN mom ON mom.reviewId = review.reviewId GROUP BY review.reviewForum";
$result1 = mysql_query($SQL1);
$data1 = array();
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['reviewForum'];
}
$result2 = mysql_query($SQL1);
$data2 = array();
while ($row = mysql_fetch_array($result2)) {
$data2[] = $row['Approved'];
}
$result3 = mysql_query($SQL1);
$data3 = array();
while ($row = mysql_fetch_array($result3)) {
$data3[] = $row['Not_Approved'];
}
$result4= mysql_query($SQL1);
$data4 = array();
while ($row = mysql_fetch_array($result4)) {
$data4[] = $row['Cancelled'];
}
?>
<script type="text/javascript">
$(document).ready(function() {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'TC REVIEW RESULT STATS'
},
xAxis: {
categories: [<?php echo join($data1, ',') ?>],
},
yAxis: {
min:0
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 50,
y: 35,
floating: true,
shadow: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [ {
name: 'Approved',
data: [<?php echo join($data2, ',') ?>],
pointStart: 0
//pointInterval
},
{
name: 'Unapproved',
data: [<?php echo join($data3, ',') ?>],
pointStart: 0
//pointInterval
},
{
name: 'Cancelled',
data: [<?php echo join($data4, ',') ?>],
pointStart: 0
//pointInterval
},
]
});
});
</script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
I suggest you start trying to render one without generated code. If that doesnt work, you might want to share that on jsfiddle and we can have a look :-). If it does work, you should compare it with the generated code.
{
name: 'Cancelled',
data: [<?php echo join($data4, ',') ?>],
pointStart: 0
//pointInterval
}, // This comma is a syntax error
]
Do you see that comma? You don't put commas before '}', because you have that in multiple places.
Take out the comma after the categories statement under xAxis.
 xAxis:  {
categories: [<?php echo join($data1, ',') ?>],
},
Should be
xAxis:  {
categories: [<?php echo join($data1, ',') ?>]
},
I think thre real reason is here:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"type="text/javascript"></script>
<script src='highcharts.js' type='text/javascript'> </script>
<script src='exporting.js' type='text/javascript'> </script>
First load jQuery, then Highcharts.

Categories