I'm trying to create a highstock's candlestick chart using php and mySQL.
this is my code so far, really appreciate if anyone can help me with this:
This my code for retrieving data from mySQL database and convert it to JSON format (datachart.php):
$conn = mysql_connect("localhost", "root", "") or die (mysql_error ());
$db = mysql_select_db ("b27sim") or die (mysql_error ());
$result=mysql_query ("SELECT date, open, high, low, close FROM mb27_daily") or die (mysql_error ());
$data = array();
$count = 0;
while ($row=mysql_fetch_array($result))
{
$newdate = strtotime($row['date']) * 1000;
$data[] = array( $newdate, (float)$row['open'], (float)$row['high'], (float)$row['low'], (float)$row['close']);
$count++;
}
echo json_encode($data);
This is the result from datachart.php:
[[1350252000000,369.72,371.02,368.09,370.22],[1349820000000,366.58,369.13,364.92,368.92],[1349733600000,367.38,369.93,366.82,368.64],[1349388000000,367.28,371.85,367.2,369.9],[1349301600000,362.75,366.24,362.22,365.61],[1349215200000,363.34,363.54,361.27,362.27],[1349128800000,360.79,362.73,360.33,361.77],[1349042400000,360.75,360.75,357.94,359.46],[1348783200000,360.62,362.69,359.84,362.5],[1348696800000,356.39,361.01,355.32,359.34],[1348524000000,358,360.39,356.34,359.7],[1348437600000,357.96,360.99,355.92,356.89],[1348178400000,359.27,360.53,356.93,360.53],[1348092000000,358.74,359.31,356.51,358.01],[1348005600000,357.97,361.82,357.24,359.86],[1347919200000,359.8,360.34,356.78,358.5],[1233010800000,119.28,122.42,119.28,121.91]]
And this is my javascript code inside index.htm:
$(function() {
$.getJSON('datachart.php', function(data) {
// create the chart
chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
},
rangeSelector : {
selected : 1
},
title : {
text : 'IB27 Price'
},
series : [{
type : 'candlestick',
name : '',
data : data,
tooltip: {
valueDecimals: 2
},
dataGrouping : {
units : [
['week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]]
]
}
}]
});
});
});
and this is my div calling the container:
<div id="container" style="height: 500px; min-width: 500px"></div>
and this is the result:
I got has not graph inside, but showing the timeline at the bottom, the date range on right top, etc.
Appreciate you guys help on this as I've been banging my head for the last 4 hours because of this... :)
Thanks,
Raz
Your data should be sorted by x (timestamps), ascending.
Related
I got started with chartJS, so I really need guidance of where to look and learn. I'm trying to display duplicated data from my SQL to chartJS.
Example:
Table name: Traffic Violations
Data I want to display: Violation types (Speeding, drifting, seatbelt, etc).
How it should be displayed: Y-axis as numbers, X-axis as violation names.
I read this: SQL count how many duplicated values of a derived table
Watched this: 1.3: Graphing with Chart.js - Working With Data & APIs in JavaScript
also watched this: How to Switch Chart to Daily, Weekly and Monthly Data in Chart js
And this: Count Total number of rows in database in php -Analytics in php
I learned few things from each, but still didn't satisfy my knowledge needs to achieve the goal I want.
I want to display the data in "Daily", "Monthly", "Yearly" format.
Sounds like that's a totally different topic, because I want the "daily" chart to reset every 24 hours, and monthly every month without deleting the data from DB. None of these videos above shows me that, nor I couldn't find what I'm looking for..
So, how to prepare my DB for chartJS?
best practice to fetch data and show it in the chart?
Here is what I have so far:
<?php
header('Content-Type: application/json');
require_once('./backend/config/connection.php');
$sqlQuery = "SELECT violationType, count(*) AS duplicates FROM traffic_violations GROUP BY violationType ORDER BY duplicates DESC";
$statement = $connection->prepare($sqlQuery);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
if ($row->num_rows > 0)
{
// output data of each row
while($row = $row->fetch_assoc())
{
echo $row["duplicates"]. "<br>";
}
}
else
{
}
echo json_encode($data);
?>
Chart:
const ctx = document.getElementById('chart-test').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Speeding', 'Drifting', 'Sealtbelt', 'Wrong Parking', 'Wrong Lane Drive', 'No License'],
datasets: [{
label: 'Traffic Violations',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ['rgba(255, 99, 132)'],
borderColor: ['rgba(255, 99, 132)'],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
I am trying to draw two graphs using chartjs. I want to make my life simplier by using a for loop to declare the variables required for the chart object.
The thing is I have created a 2d array, with each row storing data for current year, the next row storing data for the consecutive year and so on. I am trying to access the row of the variable using loop.
Here is my Chart obj
var canvas6= {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[1]);$i++){ -------->Note here
echo $dataAgeGrp[1][$i]; -------->And here
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx126 = document.getElementById('canvas6').getContext('2d');
window.myPie = new Chart(ctx126 , canvas6);
});
So, I tried something like this
for(var k=0;k<3;k++){
var q=26;
var canvas+q = {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[k]);$i++){
echo $dataAgeGrp[k][$i];
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx1+q = document.getElementById('canvas'+q).getContext('2d');
window.myPie = new Chart(ctx1+q , canvas+q);
});
q=q+1;
But I am getting this error
Use of undefined constant k - assumed 'k' (this will throw an Error in a future version of PHP)
How do I fix it?
If you can use PHP variables in your JavaScript code, the contrary is not possible. The only way to pass JavaScript variable to PHP code is by request (reload page with GET/POST parameters or AJAX request)
I want to constract a 3d interactive pie chart. Firstly I use google charts but unfortunately this doesn't work offline. I used charts from jpgraph, jscharts and rgraph but doesn't have the effect that I want. I want a graph which must be free, work offline and has approximately the same appearance with google graph. Any advice?
Thanks in advance!
Important I want to use results from my db. I write this code but dont work:
data: [{
name: 'Present',
y: <?php
while( $row2 = mysql_fetch_assoc($res2)){
echo $row2["COUNT(*)"];
}
}, {
name: 'absentees',
y: <?php
while( $row1 = mysql_fetch_assoc($res1)){
echo $row1["COUNT(*)"];
}
I have those queries:
SELECT COUNT(*)
FROM staff s, work w, absence a
WHERE s.id=a.id_staff
AND s.id_work=w.id
AND w.name='sales manager'
AND a.name='disease'
SELECT COUNT(*)
FROM staff s, work w, absence a
WHERE s.id=a.id_staff
AND s.id_work=w.id
AND w.name='sales manager'
AND a.name='vacation'
I try this but doesnt work
series: [{
type: 'pie',
name: 'Absent',
data: [
['Absent Illness', <?php
while( $row1 = mysql_fetch_assoc($res1)){
while( $row2 = mysql_fetch_assoc($res2)){
$row['COUNT(*)']=$row2['COUNT(*)'] - $row1['COUNT(*)'];
echo $row["COUNT(*)"];
}
}
?>],
['Absent Vacation',
<?php
while( $row1 = mysql_fetch_assoc($res1)){
echo $row1["COUNT(*)"];
}
?>]
]
}]
});
Please use highchart because it provide the varrious type of charts and you can also use it offline mode also. https://www.highcharts.com/
Let me guide to display mysql results onto the pie chart.
function functionname() {
$.ajax({
url : 'POST API LINK',
type : 'GET',
dataType : 'json',
success : function(data) {
var chart = new CanvasJS.Chart("chartContainer", {
title : {
text : "A suitable title"
},
animationEnabled : true,
zoomEnabled : false,
data : [ {
type : "pie",
dataPoints : [ {
y : data.active,
indexLabel : "Active part=" + data.active
}, {
y : data.Inactive,
indexLabel : "Inactive part=" + data.Inactive
},
]
} ]
});
chart.render();
},
error : function() {
alert('sorry!Somthing went wrong in Pie chart');
}
});
}
This is how you display MySQL results.
Here In data,I am getting active and inactive value from my DB.
For the UI, Please check this fiddle link.
Kindly let me know if you have any queries.
I am using highchart to draw the graph, but there's a problem that I can't draw the graph when I tried to replace the URL of $.getJSON('URL', function (data)) to
$.getJSON('Highchart_getData.php', function (data) there's nothing displayed.
I choose this example
http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/stock/demo/flags-placement/
Then I want to connect my mysql data to draw the graph.
JS.javascript:
$.getJSON('Highchart_getData.php', function (data) {
var lastDate = data[data.length - 1][0], // Get year of last data point
days = 24 * 36e5; // Milliseconds in a day
// Create the chart
Highcharts.stockChart('container', {
rangeSelector: {
selected: 1
},
title: {
text: '光照量歷史圖表'
},
yAxis: {
title: {
text: '單位:Lux'
}
},
series: [{
name: '當日光照量',
data: data,
id: 'dataseries',
tooltip: {
valueDecimals: 4
}
}, {
type: 'flags',
name: 'Flags on series',
data: [{
x: lastDate - 60 * days,
title: 'On series'
}, {
x: lastDate - 30 * days,
title: 'On series'
}],
onSeries: 'dataseries',
shape: 'squarepin'
}, {
type: 'flags',
name: 'Flags on axis',
data: [{
x: lastDate - 45 * days,
title: 'On axis'
}, {
x: lastDate - 15 * days,
title: 'On axis'
}],
shape: 'squarepin'
}]
});
});
Highchart_getData.php:
<?php session_start(); ?>
<?php
$hostdb = "localhost";
$userdb = "root";
$passdb = "";
$namedb = "light_care";
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
include("mysql_connect.inc.php");
$id=$_SESSION['username'];
$today= date('Y')-2000;
$today .= date('-m-d');
$arrData = array();
if($_SESSION['username'] != null)
{
$sqlID = "select * from user where username='$id'";
$resultID = mysql_query($sqlID);
$userID=array();
if($resultID === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($resultID))
{
$userID[0]=$row["ID"];
}
for( $a=0;$a<30;$a++)
{
$date= date('Y')-2000;
$date .= date('-m-d',time()-24*60*60*$a);
//$date= date('Y-m-d',time()-24*60*60*$a);
$sql = "select * from data where user_id='$userID[0]' and data_time like
'%$date%'";
$result = mysql_query($sql);
$light=array();
//echo $date;
$count=0;
$light_sum=0;
$step_sum=0;
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$lsum=array();
$ssum=array();
$Data=0;
while($row = mysql_fetch_array($result))
{
$Date=$row["data_time"];
$Data+=$row["light"];
//$light_sum+=$Data[$count];
//$DATE=$Data[$count];
$count++;
}
//echo $date;
$date= date('Y');
$date .= date('-m-d',time()-24*60*60*$a);
$DATA[0]=$date;
$DATA[1]=$Data;
array_push($arrData,$DATA);
$light_sum=0;
}
/*JSON Encode the data to retrieve the string containing the
JSON representation of the data in the array. */
$jsonEncodedData = json_encode($arrData);
print($jsonEncodedData);
//Close the database connection
$dbhandle->close();
}
// }
?>
and the ouput is:
[["2017-07-20",0],["2017-07-19",0],["2017-07-18",562],["2017-07-17",746],["2017-07-16",0],["2017-07-15",0],["2017-07-14",0],["2017-07-13",0],["2017-07-12",0],["2017-07-11",0],["2017-07-10",0],["2017-07-09",0],["2017-07-08",0],["2017-07-07",0],["2017-07-06",0],["2017-07-05",0],["2017-07-04",0],["2017-07-03",0],["2017-07-02",0],["2017-07-01",0],["2017-06-30",0],["2017-06-29",0],["2017-06-28",0],["2017-06-27",0],["2017-06-26",0],["2017-06-25",0],["2017-06-24",0],["2017-06-23",0],["2017-06-22",0],["2017-06-21",0]]
JQ.html:
<!DOCTYPE html>
<html>
<script type="text/javascript" src="https://code.jquery.com/jquery-
3.1.1.min.js"></script>
<script type="text/javascript"
src="https://code.highcharts.com/stock/highstock.js"></script>
<script type="text/javascript"
src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<body>
<div id="container" style="height: 400px; min-width: 310px"></div>
</body>
<script type="text/javascript" src="JS.js"></script>
</html>
but there's nothing being displayed :(
I have struggle for many days, but it still can't work...
Is there anyone can help me .
Thank you very much! and sorry for my poor English.
I do some calculations with below Code and after that i want to pass the values to the Chart but i can not send them i have try this:
$getStoreIDs = mysqli_query($dbConnection, "SELECT DISTINCT Stores_storeID FROM maintable WHERE Survey_surveyId = '$surveyID' ");
while ($row = mysqli_fetch_array($getStoreIDs))
{
$storeIDarray[] = $row;
}
foreach($_POST['sections'] as $selected)
{
foreach ($storeIDarray as $key => $row)
{
$storeID = $row['Stores_storeID'];
$storeNames= mysqli_query($dbConnection , "SELECT storeName FROM stores WHERE storeID = '".$row['Stores_storeID']."'");
$sectinName = mysqli_query($dbConnection , "SELECT sectionName FROM sections WHERE sectionID = '$selected' ");
$totalSections = mysqli_query($dbConnection, "SELECT SUM(itemPrice) AS totalSection FROM maintable WHERE items_Family_Sections_sectionID='$selected' AND Stores_storeID = '$storeID' AND Survey_surveyId = '$surveyID' ");
}
}
i want to pass the values of ($storeNames, $ectionName and $totalSelections)
and here is my CanvasJs code `
var chart1 = new CanvasJS.Chart("chartContainer1",
{
title:{
text: "Store Comparision"
},
animationEnabled: true,
axisY: {
title: "Total Price"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
dataPoints: [
]
}
]
});
chart1.render();`
First you need to put your javascript code before canvas chart,it renders.
How you are passing data to your view is important.Are you passing as json object or array?
If as json then need to parse in javscript before sending encoded in php.
In datapoints paraemeter you can pass like this
dataPoints: JSON.parse(<?php echo json_encode($json_managers) ?>)
Or can do via PHP before sending (A sample code snippet)
$managers = DB::table('orders')
->join('managers', 'orders.manager_id', '=', 'managers.id')
->groupBy('managers.manager_name')
->get(['managers.manager_name',DB::raw("sum(orders.sale) as sale")]);
foreach($managers as $key => $value){
$point = array("label" => $value->manager_name , "y" => $value->sale);
array_push($data_manager_points, $point);
}
$json_managers = json_encode($data_manager_points,JSON_NUMERIC_CHECK);
For more get here :
http://canvasjs.com/forums/topic/how-can-i-use-php-mysql-dynamic-data/