I am trying to plot a chart using Chart.JS with data from multiple MySql queries. However, when I tried loading it, the graph only display one month. Any idea how I can do this? Thank you. Hope you can help me
Here's the code for the queries:
//Query for graph
$applied_query = mysqli_query($link, "SELECT count(id) as 'count', monthname(date_created) as 'month' FROM data.application WHERE status ='APPLIED' AND year(date_created)= year(curdate()) GROUP BY month");
while ($row = mysqli_fetch_array($applied_query)){
$month[] = $row["month"];
$countApplied = $row['count'];
}
$verified_query = mysqli_query($link, "SELECT count(id) as 'count', monthname(date_verified) as 'month' FROM data.application WHERE status ='VERIFIED' AND year(date_verified)= year(curdate()) GROUP BY month");
while ($row = mysqli_fetch_array($verified_query)){
$month[] = $row["month"];
$countVerified = $row['count'];
}
$approved_query = mysqli_query($link, "SELECT count(id) as 'count', monthname(date_approved) as 'month' FROM data.application WHERE status ='APPROVED' AND year(date_approved)= year(curdate()) GROUP BY month");
while ($row = mysqli_fetch_array($approved_query)){
$month[] = $row["month"];
$countApproved = $row['count'];
}
$released_query = mysqli_query($link, "SELECT count(id) as 'count', monthname(date_released) as 'month' FROM data.application WHERE status ='RELEASED' AND year(date_released)= year(curdate()) GROUP BY month");
while ($row = mysqli_fetch_array($released_query)){
$month[] = $row["month"];
$countReleased = $row['count'];
}
And here's the code for the graph.
<!-- Bar Chart -->
<canvas id="barChart" style="max-height: 400px;"></canvas>
<script>
document.addEventListener("DOMContentLoaded", () => {
new Chart(document.querySelector('#barChart'), {
type: 'bar',
data: {
labels: <?php echo json_encode($month); ?>,
datasets: [{
label: 'Applied',
data: <?php echo json_encode($countApplied); ?>,
backgroundColor: [
'rgba(201, 203, 207, 0.3)'
],
borderColor: [
'rgb(201, 203, 207)'
],
borderWidth: 1,
}, {
label: 'Verified',
data: <?php echo json_encode($countVerified); ?>,
backgroundColor: [
'rgba(54, 162, 235, 0.3)'
],
borderColor: [
'rgb(54, 162, 235)'
],
borderWidth: 1
}, {
label: 'Approved',
data: <?php echo json_encode($countApproved); ?>,
backgroundColor: [
'rgba(60, 179, 113, 0.3)'
],
borderColor: [
'rgb(60, 179, 113)'
],
borderWidth: 1
}, {
label: 'Released',
data: <?php echo json_encode($countReleased); ?>,
backgroundColor: [
'rgba(255, 159, 64, 0.3)'
],
borderColor: [
'rgb(255, 159, 64)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks:{
beginAtZero: true
}
}]
}
}
});
});
</script>
<!-- End Bar CHart -->
The output should look like .
save your data to array like $month, example $countApplied = $row['count'] change to $countApplied[] = $row['count'];
while ($row = mysqli_fetch_array($applied_query)){
$month[] = $row["month"];
$countApplied[] = $row['count'];
}
Related
I have a table (name recuperare_laborator )with those columns: subject_id; uploader_id; class_id; and timestamp. I want to count all files from day by day from all table so I make this code:
$query = $this->db->query('SELECT subject_id ,uploader_id, class_id, COUNT(*) FROM recuperare_laborator GROUP BY class_id');
foreach ($query->result_array() as $row)
{
echo "<tr>";
echo "<td>" . $row['class_id'] . "</td>";
echo "<td>" . $row['COUNT(*)'] . "</td>";
echo "</tr>";
}
And this code work only to counter per class. How I made to count All project from one day?
I need to see:
Day 1 100 count
Day 2 101 count
...
And with this information I want to make a dynamic chart.
I try to make but i don't know how to implement code.
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['1','2'], //here i need day 1,day 2...
datasets: [{
data: [ '10','20'], // here i need count from day 1, count from day 2
backgroundColor: [
'rgba(67, 148, 255, 0.2)',
],
borderColor: [
'rgba(67, 148, 255, 1)',
],
borderWidth: 1
}]
},
});
</script>
The result must be:
image chart
picture with line count
#myEDU,
You need to alter your query with grouping by DATE(timestamp)
Here the SQL Fiddle as per your requirement.
I'm adding dynamic integration with php here in single controller including view,data manipulation as well as DB call, Codigniter follows MVC pattern and you need to split this to a MVC pattern.
Line chart expects data for one month in array and label too and that
we are serving through arrays $datasetarr and $datasetlbl
respectively.
Chart.js DOC
Dynamic Integration
public function index()
{
?>
<!DOCTYPE html>
<html>
<head>
<title>Chart</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<?php
$datasetarr = array(null);
$datasetlbl = array(0);
$month = date("m");
$mname = date("F");
$start = $end = strtotime(date("Y-m-01"));
$this->load->database();
$query = $this->db->query('SELECT COUNT(id) AS cnt, DATE(`timestamp`) AS dt FROM `recuperare_laborator` AS t1 GROUP BY dt HAVING MONTH(dt) = "'.$month.'" ORDER BY dt ASC');
$res = $query->result_array();
if($res){
$count_dt = array_column($res, 'dt');
$count_array = array_column($res, 'cnt');
$maxdt = max($count_dt);
//need to pass the month no in which you need.For eg: 05. Here i'm passing current month.
while ( $start <= $end ) {
$cdate = date('Y-m-d', $end);
$key = array_search($cdate, $count_dt);
if($key !== false){
$datasetarr[] = (int)$res[$key]['cnt'];
}else{
$datasetarr[] = 0;
}
$datasetlbl[] = date('d', $end);
$end = strtotime("+1 day", $end);
if( max($count_dt) < date('Y-m-d', $end) || $month != date('m', $end)){
break;
}
}
$datasetlbl[] = date('d', $end);
$datasetarr[] = null;
?>
<table class="table table-striped">
<thead>
<tr>
<td>count</td>
<td>date</td>
</tr>
</thead>
<tbody>
<?php
foreach ($res as $row)
{
echo "<tr>";
echo "<td>" . $row['cnt'] . "</td>";
echo "<td>" . $row['dt'] . "</td>";
echo "</tr>";
}
?>
</tbody>
</table>
<canvas id="line-chart" width="800" height="450"></canvas>
<?php
}
?>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
<?php if($res){ ?>
new Chart(document.getElementById("line-chart"), {
type: 'line',
data: {
labels: <?php echo json_encode($datasetlbl); ?>,
datasets: [{
data: <?php echo json_encode($datasetarr); ?>,
label: "<?php echo $mname; ?>",
borderColor: "#515fcf",
backgroundColor: "#515fcf",
fill: false
}
]
},
options: {
title: {
display: true,
text: 'Activity report 01 - <?php echo date("d", $end); ?>'
},
elements: {
point:{
radius: 0,
hoverRadius: 5
}
},
scales : {
xAxes : [ {
display: true,
scaleLabel: {
display: true,
labelString: 'Day'
},
gridLines : {
display : false
}
} ],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Number of files submitted'
},
ticks: {
max: <?php echo (ceil((max($count_array)) / 10) * 10)+10; ?>,
min: 0,
stepSize: 10
}
}]
}
}
});
<?php } ?>
});
</script>
</body>
</html>
<?php
}
Static Chart
$(function() {
new Chart(document.getElementById("line-chart"), {
type: 'line', data: {
labels: [0, "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17"], datasets: [ {
data: [null, 21, 1, 0, 0, 0, 8, 0, 24, 0, 0, 0, 0, 0, 0, 0, 1, null], label: "May", borderColor: "#515fcf", backgroundColor: "#515fcf", fill: false
}
]
}
, options: {
title: {
display: true, text: 'Activity report 01 - 17'
}
, elements: {
point: {
radius: 0, hoverRadius: 5
}
}
, scales: {
xAxes: [ {
display: true, scaleLabel: {
display: true, labelString: 'Day'
}
, gridLines: {
display: false
}
}
], yAxes: [ {
display: true, scaleLabel: {
display: true, labelString: 'Number of files submitted'
}
, ticks: {
max: 30, min: 0, stepSize: 10
}
}
]
}
}
}
);
}
);
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
<table class="table table-striped">
<thead>
<tr>
<td>count</td>
<td>date</td>
</tr>
</thead>
<tbody>
<tr>
<td>8</td>
<td>2020-05-01</td>
</tr>
<tr>
<td>1</td>
<td>2020-05-02</td>
</tr>
<tr>
<td>8</td>
<td>2020-05-06</td>
</tr>
<tr>
<td>24</td>
<td>2020-05-08</td>
</tr>
<tr>
<td>1</td>
<td>2020-05-16</td>
</tr>
</tbody>
</table>
<canvas id="line-chart" width="800" height="450"></canvas>
</div>
</div>
</div>
If you want to fetch particular months data with MySQL query and want to avoids data manipulation process with PHP code, you can use the following query. Here you just need to pass month and year to the query in different places.In this query im fetching data for 2020 May. Added in Fiddle too
Ref
SELECT t1.*, COUNT(t2.id) AS cnt FROM (SELECT dt
FROM
(
SELECT
MAKEDATE('2020',1) +
INTERVAL ('05'-1) MONTH +
INTERVAL daynum DAY dt
FROM
(
SELECT t*10+u daynum
FROM
(SELECT 0 t UNION SELECT 1 UNION SELECT 2 UNION SELECT 3) A,
(SELECT 0 u UNION SELECT 1 UNION SELECT 2 UNION SELECT 3
UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
UNION SELECT 8 UNION SELECT 9) B
ORDER BY daynum
) AA
) AAA
WHERE MONTH(dt) = '05' ORDER BY dt) AS t1 LEFT JOIN `recuperare_laborator` AS t2 ON dt = DATE(`timestamp`) GROUP BY dt HAVING MONTH(dt) = '05' ORDER BY dt ASC;
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!
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.
Somebody can help me. I'm new in php and highcharts. I tried to populate my chart using mysql and php, but when I tried to run it, the chart didn't appear, I only sse a blank web page. And there's no error appeared.
Her's my codes (sorry for messy code):
<!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.8.2/jquery.min.js"></script>
<script src="../../js/highcharts.js"></script>
<script src="../../js/modules/exporting.js"></script>
</head>
<body>
<?php
include "config.php";
$SQL1 = "SELECT * FROM pos";
$result1 = mysql_query($SQL1);
$data1 = array();
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['name'];
$data2[] = $row['Qty'];
}
?>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
type: 'column',
margin: [ 50, 50, 100, 80]
},
title: {
text: 'List of POS'
},
credits: {
enabled: false
},
xAxis: {
categories: [<?php echo join($data1, "','"); ?>],
labels: {
rotation: -45,
align: 'right',
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'No. of Ticket'
}
},
legend: {
enabled: false,
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 50,
y: 35,
floating: true,
shadow: true
},
tooltip: {
pointFormat: '<b>{point.y:.1f} tickets</b>',
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Qty',
data: ['<?php echo join($data2, "','"); ?>'],
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
x: 4,
y: 10,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif',
textShadow: '0 0 3px black',
}
}
}]
});
});
</script>
<div id="container" style="min-width: 500px; height: 400px; margin: 0 auto"></div>
</body>
</html>
And here's my config.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "pos";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>
Blank pages usually mean syntax errors. You should switch error_reporting on.
The errors are in the use of your echo statements where you construct the json. The error is that you are missing semi colons in both the echo statements.
Replace <?php echo join($data1, ',') ?> with <?php echo join($data1, ','); ?>
Similarly for $data2:
Replace <?php echo join($data2, ',') ?> with <?php echo join($data2, ','); ?>
Another improvement you could make in the following block:
<?php
include "config.php";
$SQL1 = "SELECT * FROM pos";
$result1 = mysql_query($SQL1);
$data1 = array();
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['name'];
}
$result2 = mysql_query($SQL1);
$data2 = array();
while ($row = mysql_fetch_array($result2)) {
$data2[] = $row['Qty'];
}
?>
Instead of executing query twice to build two arrays, you could get rid of one of the queries and build both the arrays from the same query result:
<?php
include "config.php";
$SQL1 = "SELECT * FROM pos";
$result1 = mysql_query($SQL1);
$data1 = array();
$data2 = array();
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['name'];
$data2[] = $row['Qty'];
}
?>
Note: The php mysql extension is deprecated as of PHP 5.5.0, you should be using either MySQLi or PDO_MySQL.
Please Try Example as below. I think it can help you
SQL Table
CREATE TABLE IF NOT EXISTS `sales` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`month` varchar(200) DEFAULT NULL,
`amount` varchar(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=118 ;
INSERT INTO `sales` (`id`, `month`, `amount`) VALUES
(24, 'Apr', '15'),
(25, 'May', '40'),
(26, 'Jun', '26'),
(27, 'Jul', '31'),
(28, 'Aug', '39'),
(29, 'Sep', '25'),
(30, 'Oct', '27'),
(31, 'Nov', ' 32'),
(32, 'Dec', NULL);
Here we have Create new table and insert some data in it. Now Data will look as below
index.php
<head>
<meta name="Gopal Joshi" content="Highchart with Mysql" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Highchart with Mysql Database</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/setup.js"></script>
<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
<script src="js/highcharts.js"></script>
<div id="sales" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
setup.js
var chart;
$(document).ready(function() {
var cursan = {
chart: {
renderTo: 'sales',
defaultSeriesType: 'area',
marginRight: 10,
marginBottom: 20
},
title: {
text: 'Highchart With Mysql',
},
subtitle: {
text: 'www.spjoshis.blogspot.com',
},
xAxis: {
categories: ['Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar']
},
yAxis: {
title: {
text: 'Average'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
crosshairs: true,
shared: true
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 30,
borderWidth: 0
},
plotOptions: {
series: {
cursor: 'pointer',
marker: {
lineWidth: 1
}
}
},
series: [{
color: Highcharts.getOptions().colors[2],
name: 'Test Colomn',
marker: {
fillColor: '#FFFFFF',
lineWidth: 3,
lineColor: null // inherit from series
},
dataLabels: {
enabled: true,
rotation: 0,
color: '#666666',
align: 'top',
x: -10,
y: -10,
style: {
fontSize: '9px',
fontFamily: 'Verdana, sans-serif',
textShadow: '0 0 0px black'
}
}
}],
}
//Fetch MySql Records
jQuery.get('js/data.php', null, function(tsv) {
var lines = [];
traffic = [];
try {
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
date = line[0] ;
amo=parseFloat(line[1].replace(',', ''));
if (isNaN(amo)) {
amo = null;
}
traffic.push([
date,
amo
]);
});
} catch (e) { }
cursan.series[0].data = traffic;
chart = new Highcharts.Chart(cursan);
});
});
s will import data from mysql from data.php and add to chart which is create previously in js.
data.php
$con=mysql_connect('localhost','root','');
mysql_select_db("test", $con);
$result=mysql_query('select * from sales order by id');
while($row = mysql_fetch_array($result)) {
echo $row['month'] . "\t" . $row['amount']. "\n";
}
our chart is fully loaded .with mysql records and output will look li below
Output
its example of area chart, you can change type of chart by changing defaultSeriesType: 'area'
Click Here for more Example with source.
I think your supposed to have single quotes around this
categories: [<?php echo join($data1, ',') ?>],
Should be
categories: ['<?php echo join($data1, ',') ?>'],
Even if this is an old thread, this might have nothing to do with Highcharts, I'v just noted the final phrase in your error message:
"...Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given
in C:\xampp\htdocs\otrs\chart\graphs\pos\index.php on line 22"
tipically has to do with a query that fails returning FALSE instead of a rowset. You should take a look at this related question.
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>