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;
Related
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'];
}
I don't know this is the right way to use the code or not. I am fetching the records from the database and displaying them on the page when refresh or reload the page. I have only 500 records on my table as of now.
But when I reload or refresh the page then It's taking almost 40 sec (sometimes it's talking 1 min) to display the records on the screen.
Also sometimes I am getting the error
Lost connection to MySQL server during query
I refer this link for above issue
Error Code: 2013. Lost connection to MySQL server during query. I checked accepted answer but that is not working for me.
I am using below code
index.php
<table id="workInProgress" class="table table-striped table-bordered display" style="width:100%">
<thead>
<tr class="table-column-heading">
<th>Order no</th>
<th>Lead Owner</th>
<th>Company</th>
<th>Customer</th>
<th>Product</th>
<th>Bank</th>
<th>Remark</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Script
Note: I have the below script on the index.php page
$('#workInProgress').DataTable( {
initComplete: function (d) {
this.api().columns([7]).every(function () {
var column = this;
var Jobs = $("#table th").eq([d]).text();
var select = $('<select class="drop-down"><option value="">ALL</option></select>')
.appendTo($(column.header()))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
},
language: {
sLengthMenu: "Show _MENU_",// remove entries text
searchPlaceholder: "Search",
emptyTable: "No record found",
search:""
},
"autoWidth": false,
"ordering": false,// remove sorting effect from header
"processing": true,
// "serverSide": true,
"scrollX": true,
"pageLength": 25,
"paging": true,
"ajax": {
"url" : baseUrl + "/Customer_control/workInprocess",
"type" : "POST"
},
"columns": [
{ "data": "orderno" },
{ "data": "Lead_owner" },
{ "data": "companyname" },
{ "data": "customername" },
{ "data": "producttype" },
{ "data": "bankname" },
{ "data": "remark" },
{ "data": "is_leadConfirm" },
{ "data": "action" }
],
"columnDefs": [
{ width: '14%', targets: 0 },
{ width: '13%', targets: 1 },
{ width: '13%', targets: 2 },
{ width: '10%', targets: 3 },
{ width: '8%', targets: 4 },
{ width: '12%', targets:5 },
{ width: '9%', targets: 6 },
{ width: '8%', targets: 7 },
{ width: '14%', targets: 8 }
]
});
Controller
public function workInprocess(){
$order_list=$this->Customer_model->workInprocess_lead();
// Datatables Variables
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$data['draw'] = 1;
$data['recordsTotal'] = count($order_list);
$data['recordsFiltered'] = count($order_list);
$data['data'] = [];
$i=1;
foreach ($order_list as $key => $row)
{
if ($row->f_filestatus==2) {
$leadConfirm='Submit';
}
else if ($row->f_filestatus==3) {
$leadConfirm='Pending';
}
else if ($row->f_filestatus==4) {
$leadConfirm='PD';
}
else if(($row->f_filestatus==1)|| ($row->f_filestatus==5)){
$leadConfirm='Approved';
}
else{
$leadConfirm='';
}
$action='<select name="pp_fileStatus[]" class="form-control multipleselect">
<option value="" disabled selected>File Status</option>
<option value="8" '. ($row->f_filestatus == "1"?'selected':'').' >Approved</option>
<option value="2" '. ($row->f_filestatus == "2"?'selected':'').' >Submit</option>
<option value="3" '. ($row->f_filestatus == "3"?'selected':'').' >Pendency</option>
<option value="5" '. ($row->f_filestatus == "4"?'selected':'').' >PD</option>
</select>';
$arr_result = array(
"orderno" => $row->order_no.'-'.$row->b_orderno,
"Lead_owner" => $row->empfirstname.' '.$row->emplastname,
"companyname" => $row->companyname,
"customername" => $row->c_firstname.' '.$row->c_lastname,
"producttype" => strtoupper($row->producttype),
"bankname" => $row->bankname,
"remark" => $row->f_remark,
"is_leadConfirm" => $leadConfirm,
"action" => '<ul class="lbp_actionslist">'.$action.'</ul>'
);
$data['data'][] = $arr_result;
}
//echo "<pre>";
//print_r($data);
echo json_encode($data);
exit;
}
Model
public function workInprocess_lead(){
if($this->session->userdata['login_session']['access_role']==5){
$where="f.f_filestatus NOT IN(1,8,9) AND tbl_lead.leadstatus=1 AND tbl_lead.createby='".$this->session->userdata['login_session']['id']."'";
}
else if($this->session->userdata['login_session']['access_role']==3){
$where="f.f_filestatus NOT IN(1,8,9) AND tbl_lead.leadstatus=1 AND tbl_lead.createby='".$this->session->userdata['login_session']['id']."' OR f.f_filestatus NOT IN(1,8,9) AND tbl_lead.leadstatus=1 AND tbl_bankdata.rm_name='".$this->session->userdata['login_session']['id']."'";
}
else{
$where="f.f_filestatus NOT IN(1,8,9) or f.f_filestatus IS NULL AND tbl_lead.leadstatus=1 ";
}
$result="SELECT *, `tbl_employee`.`firstname` as `empfirstname`, `tbl_employee`.`lastname` as `emplastname` FROM `tbl_lead` LEFT JOIN `tbl_bankdata` ON `tbl_lead`.`c_id`=`tbl_bankdata`.`lead_id` JOIN `tbl_bankname` ON `tbl_bankname`.`b_id`=`tbl_bankdata`.`b_bankname` left join tbl_fileStatus f
on tbl_bankdata.bank_id=f.f_bankid
and f.date_of_created = (
select max(date_of_created)
from tbl_fileStatus f1
where f1.f_bankid = f.f_bankid
) JOIN `tbl_employee` ON `tbl_lead`.`createby`=`tbl_employee`.`id` WHERE ".$where."ORDER BY tbl_lead.date_of_created DESC";
$getQuery= $this->db->query($result);
return $getQuery->result();
}
You can use the server-side data table you can try this https://datatables.net/
I am getting temperature from MySQL DB and Now I want to plot graph for the same over last 3 days. But the graph doesnt get plotted .
Here is the code for two files.
//Sql.php
<?php
// if you want to send request from a html file stored
// locally uncomment the line below
header('Access-Control-Allow-Origin: *');
// in the commands "mysql_..." change the following:
// xxxx - your SQL server address (np: www.abc.com)
// yyyy - user name
// zzzz - password
// qqqq - database name
// watch out for the capital letters!
mysql_connect("192.168.100.107:3306", "root", "hannan786") or die(mysql_error());
mysql_select_db("pi") or die(mysql_error());
// describe the date ragne - here: the last 3 days
$phpdate=time()- (3*24 * 60 * 60);
$datefrom = date( 'Y-m-d H:i:s', $phpdate );
$dateto = date( 'Y-m-d H:i:s', time() );
$data = mysql_query("SELECT * FROM temp WHERE `time` > '$datefrom'
AND `time` < '$dateto' ORDER BY time ASC") or die(mysql_error());
$rowcount = mysql_num_rows($data);
$counter=1;
// prepare the answer needed by Highcharts:
echo '{
"title": {"text": "temperature"},
"chart": {"renderTo": "container"},
"series": [{"name": "temperature", "data":[';
// fill the data from the database,
// here - the data of interest is stored in column "Temp4":
while($r = mysql_fetch_assoc($data)) {
echo '['.strtotime($r["time"])*1000 . ', '.$r["temperature"]/10 .']';
if($counter < $rowcount){
echo ", ";
}
$counter=$counter+1;
}
// finalize the answer
echo' ]}]}';
mysql_free_result($data);
?>
And this is the another page , Which is index.html , where I want to plot the graph .
<!DOCTYPE HTML>
<html>
<head>
<html xmlns="http://www.w3c.org/1999/xhtml"; xml:lang="pl" lang="pl">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Hannan</title>
<!-- pliki js znajdziesz na www.jquery.com i www.highcharts.com-->
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="js/highcharts.js"></script>
<script type="text/javascript" src="js/themes/grid.js"></script>
<script src="https://code.highcharts.com"></script>
<script type="text/javascript">
var options;
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
options = {
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%e of %b',
hour: '%H:%M<br>%d %b'
}
},
yAxis: [{
title: {
text: null
},
labels: {
align: 'left',
x: 3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}, {
linkedTo: 0,
gridLineWidth: 0,
opposite: true,
title: {
text: null
},
labels: {
align: 'right',
x: -3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}],
legend: {
align: 'left',
verticalAlign: 'top',
y: 0,
floating: true,
borderWidth: 0
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%a, %d.%b %H:%M', this.x)+'<br><b>'+ this.series.name +' '+ this.y +'°C</b>';
}
},
plotOptions: {
series: {
cursor: 'pointer',
marker: {
enabled: false,
lineWidth: 1
}
}
}
};
$.getJSON("sql.php", function(json) {
var options1 = $.extend(json, options);
chart = new Highcharts.Chart(options1);
});
});
</script>
</head>
<body>
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The charts are using HighChart Library. Please help me out if you have any idea , Why the graph or chart isint working properly.
Thank You .
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.
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.