High chart date time conversion showing wrong values - php

Below is my simple graph on high charts. Everything appears fine but only problem I have now my data is just two 2012-05-26 01:00:00, 200 and 2012-05-26 02:00:00,300. The y-axis appears fine. But on the x-axis it appear the time as start at 17:00 and ends at 18:00 and it does not even show the date even. What could be the problem?
<?php
define('DB_HOST', '*******');
define('DB_USER', 'user1');
define('DB_PASSWORD', 'test1');
define('DB_DATABASE', 'db1');
$dbcnx = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db('db1');
$sql = "select unix_timestamp(datetime1) as datetime1, value1 from data";
$result = mysql_query($sql,$dbcnx);
$data = array();
while ($row = mysql_fetch_array($result)) {
//extract $row;
//$datetime1 = $row['dateTime1']*1000;
$datetime = $row['datetime1']*1000;
//echo $datetime;
echo $row['value1'];
$val = $row['value1'];
// convert from Unix timestamp to JavaScript time
$data[] = "[$datetime, $val]";
}
?>
<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.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$(document).ready(function() {
//alert("TS");
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25
},
series:
[{
data: [<?php echo join($data, ',') ?>]
}],
xAxis: { type: 'datetime'}
});
});
});
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>

I have no idea what data you are passing the highchart. By the sounds of it you are only passing it two data points. Did you verify that the query is pulling the data you want? If so, can you post here the data that should be in the highchart? Also, can you post here the highcharts that is generated in the view source of the webpage?
As far as the xaxis labels, since they are of datetime format, then the chart will render them the best way it sees fit. If you don't like the way they are rendered, you can control the datetime formats of the chart using dateTimeLabelFormats. You can also control the interval of the dates shown using tickInterval.

Related

Reset While loop value in PHP

I have a php loop, but it keeps printing the value next to each other instead of clearing the first loop value and replacing it with the new loop value. Here is my code.
while (1==1) {
$a=array("red","green","blue","yellow","brown");
$x=array_rand($a,3);
sleep(5);
print $a[$x[0]];
}
Basically it just needs to echo out a new random value on its own every 5 seconds, currently it doesn't remove the old value.
Try use jquery, the below example is for random numbers.
<script>
var id = window.setInterval(function(){randomNumber();},1000);
function randomNumber()
{
var rand = Math.floor(Math.random()*6);
//Do whatever you want with that number
$('#holder').html(rand);
}
</script>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>Random Number</title>
</head>
<body>
<div id='holder'></div>
</body>
</html>
For random text
var names = ['test1', 'test2', 'test3', 'test4'];
setInterval(function() {
var rand = Math.floor(Math.random() * 4);
document.getElementById("name").innerHTML = names[rand];
}, 2000);
<div id="name">test</div>
I am not sure if i understand what you are trying to accomplish, but I think this is what you are trying to do.
$a=array("red","green","blue","yellow","brown");
while (count($a)) {
$x=array_rand($a);
sleep(5);
echo chr(13). $a[$x];
}

Reading a file using ftp in PHP

I am trying to read a csv file in a ftp server using php .
Below is my code:-
maps.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Circles</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
// This example creates circles on the map, representing
// populations in North America.
// First, create an object containing LatLng and population for each city.
var citymap = [];
var temp = [];
<?php
$data = array();
$file = fopen("ftp://b7_15716007:xxxxxx#ftp.byethost7.com/htdocs/data.csv","r");
while(!feof($file))
{
$data = fgetcsv($file);
?>
temp.push("<?php echo $data[0]; ?>");
temp.push("<?php echo $data[1]; ?>");
temp.push("<?php echo $data[2]; ?>");
temp.push("<?php echo $data[3]; ?>");
citymap.push(temp);
console.log(citymap);
temp = [];
<?php
}
fclose($file);
?>
var cityCircle;
function initialize() {
// Create the map.
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
var fillcolor=[];
fillcolor[0]='#FF0000';fillcolor[1]='#FFFF00'; fillcolor[2]='#FF00FF'; fillcolor[3]='#00FF00';
var loop=0;
for (i = 0; i < citymap.length; i++) {
var populationOptions = {
strokeColor: '#000000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: fillcolor[loop],
fillOpacity: 0.35,
map: map,
center: new google.maps.LatLng(citymap[i][1], citymap[i][2]),
radius: Math.sqrt(citymap[i][3]) * 100000
};
// Add the circle for this city to the map.
cityCircle = new google.maps.Circle(populationOptions);
// cityCircle = new google.maps.Circle(populationOptions1);
loop=loop+1;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
This code has to read the values in csv and represent them in a google map api .
But the code is not working .
Can anyone please help me fix this .
The link for the csv is
Even after passing the url with authentication I dont get the map being displayed .
You cannot just open password protected ftp resource like that.. You must use password for entering there.
Please, try to use some authentication functions like:
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// try to download $server_file and save to $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
echo "Successfully written to $local_file\n";
} else {
echo "There was a problem\n";
}
Refer to: http://php.net/manual/en/function.ftp-get.php for more information.

session variable doesnt save after redirecting on same page

Index.php
<?php
session_start();
require 'components/database.php';
require 'components/user.php';
$_SESSION['viewer_id'] = $_GET['viewer_id'];
echo $_SESSION['viewer_id'];
?>
<!DOCTYPE html>
<html lang="ru">
<head>
<title>Entropia Universe - Приложение</title>
<meta charset="utf-8">
<link href="template/default/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="template/default/css/style.css" rel="stylesheet" media="screen">
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="http://vk.com/js/api/xd_connection.js" type="text/javascript"></script> <!--Подключаем API-->
<script src="template/default/js/bootstrap.min.js"></script>
<script type="text/javascript" charset="utf8" >
$(document).ready(function() { /*Когда загрузится вся страница*/
VK.init({apiId:3822299},function() {
console.log("init");
}, function() {
// API initialization failed
// Can reload page here
}, '5.0');
var viewer_id = 0;
var auth_key = 0;
var image ='';
/*Записываем в переменные id посетителя и ключ*/
viewer_id = '<?=$_SESSION['viewer_id']?>';
auth_key = '<?=$_SESSION['auth_key']?>';
VK.api("users.get", {uids:viewer_id,fields:"photo_big"}, function(data) {
$('#user-avatar').html("<img src='" + data.response[0].photo_big + "' class='img-polaroid'>");
//$("#info").html("<img src='" + data.response[0].photo_big + "'>" + data.response[0].first_name + ' ' + data.response[0].last_name + ' ' + viewer_id); /*в div с id=info записываем аватарку, имя, фамилию*/
});
});
</script>
</head>
<body>
<?php
$db = new Database('144.76.6.45','5432','eu','eu','eu123');
$db->querySelect("SELECT * FROM users WHERE vk_id = ".$_SESSION['viewer_id']."");
$row = $db->STH->fetch();
if(empty($row)){
require 'template/default/not_logged.php';
}
else {
require 'template/default/logged.php';
}
?>
</body>
</html>
From API i'm getting variables via GET method. Please don't ask what API, there is no need to write about it. Ok.. There creates a session['viewer_id'] with get['viewer_id'] value. All is ok, the code works, the session displays ok. When i go to other page, the session is still visible, but when i go BACK to index.php session['viewer_id'] dissapears, and it shows login form, but it shoudnt.
Can anybody tell me whats the problem?
Change your code to this:
if(isset($_GET['viewer_id'])
$_SESSION['viewer_id'] = $_GET['viewer_id'];
echo $_SESSION['viewer_id'];
And you do not overwrite your value in the session if $_GET['viewer_id'] is not set.

Highstock - Creating an OHLC graph by csv created using php

I'm having some problems with importing the csv in order to get the highstock graph.
I'm using the same code as the ohlc example (which works fine locally) but with another CSV which is created on my localhost by php.
PHP to get the CSV
<?PHP
// Declare the new variable as an array
$arrCSV = array();
// Open the CSV file
if (($handle = fopen("http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=7&e=7&f=2012&g=d&a=8&b=7&c=1984&ignore=.csv", "r")) !==FALSE)
{
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row
$c = count($data);
//print $c . "<BR>"; // <------ 7 o numero de colunas
//Populate the array
If ($key != 0) {
$arrCSV[$key-1][0] = strtotime($data[0]); //Time
$arrCSV[$key-1][1] = $data[1]; //Open
$arrCSV[$key-1][2] = $data[2]; //High
$arrCSV[$key-1][3] = $data[3]; //Low
$arrCSV[$key-1][4] = $data[6]; //Adj Close
$arrCSV[$key-1][5] = $data[5]; //Volume
}
$key++;
} // end while
$keymax = $key;
// Close the CSV file
fclose($handle);
} // end if
print "?(/* AAPL historical OHLC data from the Google Finance API */<BR>";
echo json_encode($arrCSV,JSON_NUMERIC_CHECK);
print ");";
?>
Code to import and create the graph:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('http://localhost/teste03.php', function(data) {
// create the chart
chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 2
},
title : {
text : 'AAPL Stock Price'
},
series : [{
type : 'ohlc',
name : 'AAPL Stock Price',
data : data,
dataGrouping : {
units : [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]]
}
}]
});
});
});
</script>
</head>
<body>
<script src="js/highstock.js"></script>
<script src="js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
In the end it just get me a blank page...
Is this caused by being using localhost? The order of the array (descendent instead of ascendent)?
Help?
Update: json_encode added but still doesn't work.
FURTHER EDITED
Seems that you might have ajax issues, try doing an isolated test by
Using the SimpleTest.php (refer OLD section for code) and hosting it on the same server as your current teste03.php, and access the chart from it
$.getJSON('http://localhost/SimpleTest.php', function(data) {
...
}
OR
<script type="text/javascript">
$(function() {
// $.getJSON('http://localhost/teste03.php', function(data) {
var data= [[1000000,1,2,3,4],[2000000,3,2,3,4],[1000000,1,2,3,4]];
// create the chart
chart = new Highcharts.StockChart({
...
If any of the above approaches work, means that you have an ajax issue and not a highcharts issue.
EDITED (based on your comment about the json that was returned)
The timestamp values in the data need to be in ascending order. From your following json
[[1344290400,622.77,625,618.04,618.26,10373100],[1344204000,617.29,624.87,615.26‌​,619.89,10789400]
1344290400>1344204000 hence wont work.
OLD
use the json_encode method for the json formation.
What you need to pass to it is, an array of array where the outer array is of the size same as the number of rows in the CSV, and each element of this outer array is another array with 5 elements, viz. timestamp, open, high, low, close.
SimpleTest.php:
<?php
// JSON header
header('Content-type: application/json');
// Do not cache the response
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
// Parse CSV, and populate the 5 arrays viz. $timeStamp, $open, $high, $low, $close
$count=3;
$timeStamp=array(1000000,2000000,3000000); // In ascending order of time
$open=array(5,10,15);
$high=array(10,15,20);
$low=array(0,5,10);
$close=array(8,12,18);
$dataArray=array(); // Outer array of array
for( $i=0; $i<$count; $i++ ){
// push an array into $dataArray for each data group
$dataArray[] = array($timeStamp[$i], $open[$i], $high[$i], $low[$i],$close[$i]);
}
echo json_encode($dataArray); // Encode php array of array into json and echo/print it to output
?>
Looking at your code, i think you can tweak you $arrCSV to transform into the required array.

Retrieve data from mysql by php to create flot graph

Hi i am trying to retrieve data from mysql database to create flot graph
can anyone walk me through this procedure or give me an idea of what to do
thanks
You probably want something like this. I haven't used flot but I looked at the example here.
<?php
//create array of pairs of x and y values
$dataset1 = array();
while ($row = mysql_fetch_assoc()) { //or whatever
$dataset1[] = array( $row['xvalue'], $row['yvalue'] );
}
?>
<script type="text/javascript">
//put array into javascript variable
var dataset1 = <?php echo json_encode($dataset1); ?>;
//plot
$(function () {
$.plot($("#placeholder"), [ dataset1 ]);
});
</script>
Adding upon the example from #Tom Haigh:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../jquery.flot.js"></script>
</head>
<body>
<h1>Flot Examples</h1>
<div id="placeholder" style="width:600px;height:300px;"></div>
<?php
$server = "localhost";
$user="user";
$password="password";
$database = "some_database";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
query = "SELECT x_axis_values, y_axis_values FROM some_table";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($row['x_axis_value'],$row['y_axis_value']);
}
?>
<script type="text/javascript">
$(function () {
var dataset1 = <?php echo json_encode($dataset1); ?>;
$.plot($("#placeholder"), [ dataset1 ]);
});
</script>
</body>
</html>
as #Tom Haigh say work well, but you need to add another code to work well, I was using the example, but I discover in the source code it add to the result quotes " so to avoid this just add the: intval to the array, example:
<?php
$query = "SELECT valx, valy FROM chart";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$d2[] = array (intval($row['valx']),intval($row['valy']));
}
?>
This depends largely on your environment and requirements. There's lots of free tools out there you can use. One example is Flot that lets you use jQuery to build graphs. There's link to documentation on the Google Code page.

Categories