Retrieve data from mysql by php to create flot graph - php

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.

Related

Get <script> in head HTML using DOM Parser

I'm currently using DOM Parser for my project. Also, I'm using CURL in php to scraping the website. I want to get a value from the script tag in the head of the HTML I get. But I really confused how to do that. If run the code bellow :
$data_dom = new simple_html_dom();
$data_dom->load($html);
foreach($data_dom->find('script') as $script){
echo $script->plaintext."<br>";
}
The result was the empty value, when I inspect it, only br tag appear. I want to get everything that using script tag. Here is the head value :
<head>
I will give you the script I want to get
.....
<script type="text/javascript">
var keysearch = {"departureLabel":"Surabaya (SUB : Juanda) Jawa Timur Indonesia","arrivalLabel":"Palangkaraya (PKY : Tjilik Riwut | Panarung) Kalimantan Tengah Indonesia","adultNum":"1","childNum":"0","infantNum":"0","departure":"SUB","arrival":"PKY","departDate":"20181115","roundTrip":0,"cabinType":-1,"departureCode":"ID-Surabaya-SUB","arrivalCode":"ID-Palangkaraya-PKY"};
(function(window, _gtm, keysearch){
if (window.gtmInstance){
var departureExp = keysearch.departureCode.split("-");
var arrivalExp = keysearch.arrivalCode.split("-");
gtmInstance.setFlightData({
'ITEM_TYPE': 'flight',
'FLY_OUTB_CODE': departureExp[2],
'FLY_OUTB_CITY': departureExp[1],
'FLY_OUTB_COUNTRYCODE': departureExp[0],
'FLY_OUTB_DATE': keysearch.departDate,
'FLY_INB_CODE': arrivalExp[2],
'FLY_INB_CITY': arrivalExp[1],
'FLY_INB_COUNTRYCODE': arrivalExp[0],
'FLY_INB_DATE': keysearch.returnDate,
'FLY_NBPAX_ADL': keysearch.adultNum,
'FLY_NBPAX_CHL': keysearch.childNum,
'FLY_NBPAX_INF': keysearch.infantNum,
});
gtmInstance.pushFlightSearchEvent();
}
}(window, gtmInstance, keysearch));
var key = "rkey=10fe7b6fd1f7fa1ef0f4fa538f917811dbc7f4628a791ba69962f2ed305fb72d061b67737afd843aaaeeee946f1442bb";
var staticRoot = 'http://sta.nusatrip.net';
$(function() {
$("#currencySelector").nusaCurrencyOptions({
selected: getCookie("curCode"),
});
});
</script>
</head>
I want to get the key variable. I will use it to get the data from the website. Thanks
Depending on what the rest of the markup looks like, you may be able to just use DOMDocument and XPath, then parse out the value of the var with preg_match. This example will echo the key.
<?php
$html = <<<END
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
var keysearch = {"departureLabel":"Surabaya (SUB : Juanda) Jawa Timur Indonesia","arrivalLabel":"Palangkaraya (PKY : Tjilik Riwut | Panarung) Kalimantan Tengah Indonesia","adultNum":"1","childNum":"0","infantNum":"0","departure":"SUB","arrival":"PKY","departDate":"20181115","roundTrip":0,"cabinType":-1,"departureCode":"ID-Surabaya-SUB","arrivalCode":"ID-Palangkaraya-PKY"};
(function(window, _gtm, keysearch){
if (window.gtmInstance){
var departureExp = keysearch.departureCode.split("-");
var arrivalExp = keysearch.arrivalCode.split("-");
gtmInstance.setFlightData({
'ITEM_TYPE': 'flight',
'FLY_OUTB_CODE': departureExp[2],
'FLY_OUTB_CITY': departureExp[1],
'FLY_OUTB_COUNTRYCODE': departureExp[0],
'FLY_OUTB_DATE': keysearch.departDate,
'FLY_INB_CODE': arrivalExp[2],
'FLY_INB_CITY': arrivalExp[1],
'FLY_INB_COUNTRYCODE': arrivalExp[0],
'FLY_INB_DATE': keysearch.returnDate,
'FLY_NBPAX_ADL': keysearch.adultNum,
'FLY_NBPAX_CHL': keysearch.childNum,
'FLY_NBPAX_INF': keysearch.infantNum,
});
gtmInstance.pushFlightSearchEvent();
}
}(window, gtmInstance, keysearch));
var key = "rkey=10fe7b6fd1f7fa1ef0f4fa538f917811dbc7f4628a791ba69962f2ed305fb72d061b67737afd843aaaeeee946f1442bb";
var staticRoot = 'http://sta.nusatrip.net';
$(function() {
$("#currencySelector").nusaCurrencyOptions({
selected: getCookie("curCode"),
});
});
</script>
</head>
<body>foo</body>
</html>
END;
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$result = $xpath->query('//script');
foreach($result as $currScriptTag)
{
$currScriptContent = $currScriptTag->nodeValue;
$matchFound = preg_match('/var key = "(.*)"/', $currScriptContent, $matches);
if($matchFound)
{
/*
* $matches[0] will contain the whole line like var key = "..."
* $matches[1] just contains the value of the var
*/
$key = $matches[1];
echo $key.PHP_EOL;
}
}

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];
}

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.

I'm trying to src a js file containing XMHTTPRequest script into my HTML

If I embed my XHR file into my HTML document directly, everything works fine. As soon as I src it via
<script type="text/javascript" src="js/ajax_gallery.js">ajax_json_gallery('gallery');</script>
Nothing works, and I get no errors. I'm assuming it's something to do with the XHR being created in a separate file to the HTML. I just don't like XHR script cluttering up my HTML, I just want to load as an external JS file.
I've moved my main 3 scripts, galleryHandle.php, XHR.js, ajax_gallery.html all to the same dir level to keep things simple. And the gallery images are in a folder called "gallery", also on the same level.
Here's my code:
HTML
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/gallery.css" />
</head>
<body>
<div id="pagetop"></div>
<div id="thumbnailbox"></div>
<div id="pictureframe"></div>
<script type="text/javascript" src="XHR.js">ajax_json_gallery('gallery');</script>
</body>
</html>
JavaScript
function ajax_json_gallery(folder) {
"use strict";
var httpRequest = new XMLHttpRequest();
document.getElementById("pagetop").innerHTML = "dynamic ajax json gallery";
var thumbnailbox = document.getElementById("thumbnailbox");
httpRequest.open("POST", "galleryHandle.php", true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
var pictureframe;
pictureframe.innerHTML = "<img src='"+data.img1.src+"'>";
thumbnailbox.innerHTML = "";
for (var obj in data) {
if (data[obj].src){
thumbnailbox.innerHTML += '<div onclick="putinframe(\''+data[obj].src+'\')"><img src="'+data[obj].src+'"></div>';
}
}
}
};
httpRequest.send("folder="+folder);
thumbnailbox.innerHTML = "Loading...";
}
function putinframe(src) {
"use strict";
var pictureframe = document.getElementById("pictureframe");
pictureframe.innerHTML = '<img src = " '+src+' " >';
}
PHP
<?php
header("Content-Type: application/json");
//bring in folder name
$folder = $_POST["folder"];
//start componding json
$jsonData = '{';
//compound directory path
$dir = $folder."/";
//open directory
$dirHandle = opendir($dir);
//init while looop
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && strpos($file, '.jpg')){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
I understand there are some redundancies in my code but it's just a tutorial I'm going through to learn the basics of JSON building with POST, XHR.
Anyway, help appreciated as always.
Thanks
Explanation
FROM W3C:
<script type="text/javascript" src="myscript.js">
alert('I am pointless as I won\'t be executed');
</script>
Upon meeting this element in a page, browsers will then load the file myscript.js and execute it. Any content inside the script element itself will be skipped when you provide a src attribute. The [last] example will load the file myscript.js and execute the code in it but will not execute the alert inside the script element at all.
Solution
Try the following in your head tags:
HTML
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">
ajax_json_gallery('gallery');
</script>
<script type="text/javascript" src="XHR.js">
You can't have src attribute and javascript both in a single tag. Separate them out. Like this...
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">ajax_json_gallery('gallery');</script>

High chart date time conversion showing wrong values

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.

Categories