The code I am using is below.
I want to make a simple graph based on the data from my database table.
It is working now but I want date on the bottom axis is not appearing properly.
while the value of variable is
[25-03-15, 1236], [26-03-15, 3000], [27-03-15, 3054], [30-03-15, 4000]
that is right. But I cant get this date on the x-axis. any solution there?
The way I am getting getting this value is
<?php
$usd=$this->db->query('select transaction_date, SUM(amount) as total from transactions GROUP BY transaction_date')->result_array();
$str = '';
for($i=0; $i<count($usd); $i++){
if($i!=0){
$str = $str.', ['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}else{
$str = $str.'['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}
}
echo $str;
?>
Then I pass this data in java script like this:
var graphData = [{
data: [ <?php echo $str; ?>]
}
];
But At the end I can not get the date on x axis.
PS:
I am working on the view of codeigniter application.
Have a look at the documentation for time series data.
You need javascript timestamps. In PHP you get them simply with
strtotime($usd[$i]["transaction_date"]) * 1000
Then your data should look like this:
[1427238000000, 1236], [1427324400000, 3000], ...
For the labels on the x axis, use the timeformat options to get back the format you want:
xaxis: {
mode: "time",
timeformat: "%d-%m-%y"
}
Related
I knew the answer was going to be much simpler then I was making it out to be. I added the following if statement to the while loop.
<?php
echo "['Month', '$year1' , '$year2' , '$currentYear'],";
require('./PHPConnect.php');
$statement1 = #mysqli_query($dbc, $query1);
while($row = mysqli_fetch_array($statement1)){
if($row["Year3"] == NULL ? $row["Year3"] = 'null' : $row["Year3"] = $row["Year3"]);
echo "['".$row["Month"]."', ".$row["Year1"].", ".$row["Year2"].", ".$row["Year3"]."],";
}
mysqli_close($dbc);
?>
As an update we now know that the problem is MySql spits out NULL and javascript requires null. Any thoughts on how to accomplish getting MySql NULL int value into lowercase null.
*I was wondering if anyone can help me with this. I created a line chart to visual show company sales by month for the current year and the previous 2. It works fine, but because at this point there is 0 sales for the remaining months of the year it shows a steep drop off for that line. We don't want to see that, so I tried changing the 0s to nulls in the database and using interpolateNulls false. However when I add the interpolateNulls option the line chart breaks and no longer displays anything. Any ideas?
<script type="text/javascript">
var data;
var chart;
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
data = google.visualization.arrayToDataTable([
<?php
echo "['Month', '$year1' , '$year2' , '$currentYear'],";
require('./PHPConnect.php');
$statement1 = #mysqli_query($dbc, $query1);
while($row = mysqli_fetch_array($statement1)){
echo "['".$row["Month"]."', ".$row["Year1"].", ".$row["Year2"].", ".$row["Year3"]."],";
}
mysqli_close($dbc);
?>
]);
var options = {
backgroundColor: 'transparent',
title:'Total Sales By Month',
width:600,
height:500,
interpolateNulls: false,
legend: {position: 'bottom'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I'm trying to print out an array of dates pulled from an API, which come out formatted as YYYYmmdd, i.e. 20160701. When I convert them to a friendlier format and then go to print them in Highcharts, it actually will do a mathematical calculation based on the operator being used to separate the date elements. Obviously that's not what I want it to do. So the first date is actually performing 7 minus 1 minus 2016, resulting in the -2010. Does anyone know what is causing this?
PHP Snippet
foreach ($arr['rows'] as $item){
$dates[] = DateTime::createFromFormat('Ymd', $item[0])->format('m-d- Y');
}
Javascript Highchart Plugin
$('#myChart').highcharts({
xAxis: {
categories: [
<?php
echo implode(',', $dates);
?>
]
},
What the dates end up looking like:
The problem is that you're not injecting any quotes in the Javascript source.
What you get is something like:
$('#myChart').highcharts({
xAxis: {
categories: [ 7-1-2016 ] // <--- should be [ "7-1-2016" ]
}
});
which is evaluated as categories: [ -2010 ] on the Javascript side.
You should do:
$('#myChart').highcharts({
xAxis: {
categories: [
<?php
echo '"'.implode('","', $dates).'"';
?>
]
}
});
Or if you prefer to have this fixed in the PHP code that is building this array:
foreach ($arr['rows'] as $item){
$dates[] = DateTime::createFromFormat('Ymd', $item[0])->format('"m-d-Y"');
}
EDIT: as suggested by jlbriggs, a better approach would be to use json_encode().
At least on $dates ...
$('#myChart').highcharts({
xAxis: {
categories: <?php echo json_encode($dates); ?>
}
});
... or on the whole object passed to highcharts() (assuming it's entirely built on the PHP side):
$('#myChart').highcharts(<?php echo json_encode($highChartsObject); ?>);
I am making a kind of reservation page where you can reserve a location for a specific day, all the dates will be stored in a database for each location.
But I want to get all the dates from the database and store them in a javascript array so I can disable these dates from the datepicker on the page.
I know how to select the dates using php and mysql but I can't figure out a way to store the data in a javascript array.
This is the js code for the datepicker:
var disableddates = ["20-05-2015", "12-11-2014", "21-05-2015", "12-20-2014"];
function DisableSpecificDates(date) {
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [disableddates.indexOf(string) == -1];
}
$(function() {
$("#date1").datepicker({
beforeShowDay: DisableSpecificDates
});
});
I want the array to hold the dates from the database.
You need to fetch data from database and json_encode them
var disableddates = <?php echo json_encode($response)?> ;
You can't write JS code directly in you PHP script.
PHP runs on the server, JS runs on the client.
JS from PHP's point of view is just like HTML.
What you can do, is output this to tag.
Something like ($dates contain the disabled dates):
function outputDatePickerScript($dates) {
echo 'var disableddates = ["' . implode('","', $dates) . '"]';
echo .... // Rest of the JS script
}
Call this function before the end of your HTML Body output.
You have options like
1.to write jquery function in php scipt echo '<script></script' and store the date values in array by select & fetch statement e.g.
/*Your select statement for dates*/
while loop{
$dates .= '"'.$row["date"].'",'
}
$dates = rtrim($dates, ",");
var disableddates = ['.$dates.'];
2> Store db values in a hidden field on front html with an id and pass the value in javascript varaible by selecting id
That's only your js code, show a little of the php too.
if you're not using any fancy ajax you could use something like this:
<?php
$dates = "";
while () { //this while would be your database while
$dates .= '"'.$row["date"].'",';
}
$dates = rtrim($dates, ",");
?>
var disableddates = [<?php echo $dates; ?>];
I'm trying to create a range area chart using CanvasJS and PHP to load the data from a database.
I've created the php and it returns the values from the DB.
Here is the php:
<?php
header('Content-Type: application/json');
$con = mysqli_connect("127.0.0.1","root","pwd1","db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "select (CalYear+1) as CalYear, concat('[',REPLACE(Year1PercWC,',','.'),',',REPLACE(Year1PercBC,',','.'),']') as ResultSet, concat('Sessies: ',calyear) as Help FROM table where cat='1' and (CalYear+1)<year(now())");
while($row = mysqli_fetch_array($result))
{
$point = array("x" => $row['CalYear'] , "y" => $row['ResultSet'],"name" => $row['Help']);
array_push($data_points, $point);
}
echo json_encode($data_points);
}
mysqli_close($con);
?>
With the results:
[{"x":"2007","y":"[35.94,35.94]","name":"Sessies: 2006"},{"x":"2008","y":"[27.67,27.67]","name":"Sessies: 2007"},...,...]
The problem are the quotes in the x and y values (=string values). CanvasJS only takes numbers to create a graph. So the output should be like:
[{"x":2007,"y":[35.94,35.94],"name":"Sessies 2006"},{"x":2008,"y":[27.67,27.67],"name":"Sessies 2007"},...,...]
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="jquery.canvasjs.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("TestGraf.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
axisX: {
intervalType: "number",
title: "Year",
interval: 1,
valueFormatString: "#"
},
data: [
{
type: "rangeArea",
dataPoints: result
[{"x":2007,"y":[35.94,35.94],"name":"Sessies 2006"},{"x":2008,"y":[27.67,27.67],"name":"Sessies 2007"}] -- This is working fine
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
I'm sure there must be a way to adapt my php so that x and y are passed through as numbers instead of strings, but i'm really new at php (first time ever) and can't find the solution,especially for the second part (y).
Can anyone tell me which adaptions to make to the php and/or html file?
Thx,
This should probably work for you :
json_encode($arr, JSON_NUMERIC_CHECK);
It's probably a little too late for my answer but like Alex answered, you should use echo json_encode($data_points, JSON_NUMERIC_CHECK);
The numeric check is an option. See http://php.net/manual/en/json.constants.php
However, more understanding of how a range area chart works seems to be the problem. The range area chart has an X and 2 Y values. The 2 Y values are needed to plot the range. If you simply go to the testgraf.php file in your browser, your JSON result should be:
[{x: somevalue, y:[low_value, high_value]}]
You might have to change your sql statement to get another y value. You can do what you want with that. Anyway, this is what you should do for your php code:
Change
$point = array("x" => $row['CalYear'] , "y" => $row['ResultSet'],"name" => $row['Help']);
to:
$point = array("x" => $row['CalYear'] , "y" => $row['ResultSet', 'some_value'],"name" => $row['Help']);
If your 2 Y values don't change, you may not see a graph line diplayed. Would a line graph be more appropriate?
After some trial and error I found the following solution:
$result1 = mysqli_query($con, "select (CalYear+1) as CalYear, Year1PercWC, Year1PercBC, calyear as Help FROM table_2 where cat='1' and (CalYear+1)<year(now())");
while($row = mysqli_fetch_array($result1))
{
$point = array("x" => floatval($row['CalYear']),"y" => array(floatval($row['Year1PercWC']),floatval($row['Year1PercBC'])),"name" => floatval($row['Help']));
array_push($data_points, $point);
}
echo json_encode($data_points);
The problem was I needed to create an array for my Y-values in the array for the datapoints. In this array I could store the 2 values I needed for the graph.
After this was done I needed to transform al the numeric values to float_val so that the quotes around the values disappeared.
Thx for the help everyone :)
I would like to replicate this highcharts column graph: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-drilldown/
I'm pulling my data from a table and it looks like this.
I want the Job_Num on the x-axis where brands are in the fiddle, PercentofBudgetedHrs would be the brandsData. Now when you click a job number, it drills down to departments and shows their percentage of budgeted hrs.
I have the first part working, but I'm using different code like so: http://jsfiddle.net/98Fuq/4/
Here is what I changed in that code:
$sql = "SELECT * FROM view_percentof_budgeted WHERE PercentofBudgetedHrs < 1000 && PercentofBudgetedHrs IS NOT NULL";
$result = mysqli_query($dbc3, $sql);
while($row = mysqli_fetch_assoc($result)) {
$jobNum[] = $row['Job_Num'];
$jobData[$row['Job_Num']] = $row['PercentofBudgetedHrs'];
$jobDrillData[$row['Job_Num']][] = $row;
}
The part I changed in the JS:
var colors = Highcharts.getOptions().colors,
categories = [<?php echo join($jobNum, ',') ?>],
name = '% of budgeted hours',
level = 0,
data = [
<?php echo join($jobData, ',') ?>,
];
function setChart(name, categories, data, color, level) {
chart.xAxis[0].setCategories(categories);
chart.series[0].remove();
chart.addSeries({
name: name,
data: data,
level: level,
color: color || 'red'
});
}
How do I go about doing it the way that first fiddle I posted does it? I like my method of pulling the data from a table so I don't want to use a tsv, I'm just confused on the drilldown part. I've looked at examples but can't seem to figure it out.
Instaed of using join() I advice to prepare correct strucutre of arrays in php, then use json_encode() including JSON_NUMERIC_CHECK flag. As a result you can get this json by $.getJSON and put in highcharts.