php to highchart, how to send the right array? - php

I made this code with:
https://github.com/influxdata/influxdb-php
https://www.highcharts.com/docs/working-with-data/live-data
<?php
include('/opt/lampp/htdocs/example/vendor/autoload.php');
$host = '127.0.0.1';
$port = 8086;
$dbname = 'aTimeSeries';
/*
$client = new \InfluxDB\Client($host, $port);
$database = $client->selectDB('aTimeSeries');
*/
//the exact same thing
$database = \InfluxDB\Client::fromDSN(sprintf('influxdb://user:pass#%s:%s/%s', $host, $port, $dbname));
//query of the last value
$result = $database->query('select * from valeurs group by * order by desc limit 1');
//recup le point
$points = $result->getPoints();
// Set the JSON header
header("Content-type: application/json");
// The x value is the current JavaScript time, which is the Unix time multiplied by 1000.
$x = time() * 1000;
// The y value is a random number
//$y = rand(0,100);
$y = $points;
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
Output:
[1523603506000,[{"time":"2018-04-13T07:11:45.208943754Z","value":48}]]
But I would like this:
[1523603506000,48]
Or this:
[2018-04-13T07:11:45.208943754Z,48]
If I try to output $points only, I got only the last part of the array, but it is not what I would like either.
PS: if you have a better solution to do the same thing, maybe with nodeJS, I will surely listen

Thanks for your help,
I had another problem, but I solved it.
But still have 2 hours of lag, but it display right in highcharts now.
<?php
include('/opt/lampp/htdocs/example/vendor/autoload.php');
$host = '127.0.0.1';
$port = 8086;
$dbname = 'aTimeSeries';
//directly get the database object
$database = \InfluxDB\Client::fromDSN(sprintf('influxdb://user:pass#%s:%s/%s', $host, $port, $dbname));
//query of the last value
$result = $database->query('select * from valeurs group by * order by desc limit 1');
//get the point
$points = $result->getPoints();
//make the array right
$points = json_encode($points);
$points = json_decode($points);
//take only the seconds of the time
$points[0]->time = substr($points[0]->time, 0,20);
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied by 1000 and take the time
$x = strtotime($points[0]->time) * 1000;
// The y value take the value which is a random value
$y = $points[0]->value;
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>

Related

Fetching latest value from database even when there are no rows present

So I'm trying to fetch a points table for users to add points in by garnering their total points and adding it with the installation points, however by trying to fetch their "latest" points, new users who do not have an existing row in the table will throwback an error "InvalidArgumentException; Data Missing". This would be my code below, and are there any other ways around this?
$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first();
$points['user_id'] = $input['user_id'];
$points['points_add'] = $battery['point_installation'];
$points['points_subtract'] = 0;
$points['points_total'] = $currentpoint + $battery['point_installation'];
$points['points_source_id'] = 1;
$points['created_at'] = $mytime;
$points['updated_at'] = $mytime;
$point = Points::create($points);
$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first(); of your code return an object and you are try to perform math (addition) operation on that object which is not possible. You can update your code like below.
$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first();
$points['user_id'] = $input['user_id'];
$points['points_add'] = $battery['point_installation'];
$points['points_subtract'] = 0;
if($currentpoint != null)
{
$points['points_total'] = $currentpoint->points_total + $battery['point_installation'];
}
else {
$points['points_total'] = $battery['point_installation'];
}
$points['points_source_id'] = 1;
$points['created_at'] = $mytime;
$points['updated_at'] = $mytime;
$point = Points::create($points);

Algorithm of getting free IP address

I use yii2. And I need to find IP which is not used (is not in database) by method getFreeIPAddress. I have class like this:
class Radreply extends ActiveRecord {
const ATTRIBUTE_DEFAULT_IP_ADDRESS = 'Framed-IP-Address';
const IP_ADDRESS_MAX = '10.255.255.255'; // max value for IP
const IP_ADDRESS_MIN = '10.0.0.11'; // min value for IP
public function getIntegerIP(){ // converts IP from string to integer format
return ip2long($this->value);
}
public static function getFreeIPAddress(){
$records = self::findAll(['attribute'=>self::ATTRIBUTE_DEFAULT_IP_ADDRESS]); // get all record which contain IP address
$existIPs = ArrayHelper::getColumn($records,'integerIP'); // get array of IP which is converted to integer by method getIntegerIP
for ($integerIP = ip2long(self::IP_ADDRESS_MIN); $integerIP<=ip2long(self::IP_ADDRESS_MAX); $integerIP++){
// increasing one by one IP address in integer format from value IP_ADDRESS_MIN to value IP_ADDRESS_MAX
if (!in_array($integerIP, $existIPs)){
$stringIP = long2ip($integerIP);
$arrayDigits = explode('.', $stringIP);
$lastDigit = array_pop($arrayDigits);
if ($lastDigit!='0'){ // check if last digit of IP is not 0
return $stringIP;
}
}
}
return '';
}
}
Method getFreeIPAddress works find, but in db there are a lot of records with IP and increasing one by one IP and checking if this IP exist in db is very long way. How I can optimize this algorithm? Is there faster way to get unused IP?
I think, I've found better solution without extra table in database
class Radreply extends ActiveRecord {
const ATTRIBUTE_DEFAULT_IP_ADDRESS = 'Framed-IP-Address';
const IP_ADDRESS_MAX = '10.255.255.255'; // max value for IP
const IP_ADDRESS_MIN = '10.0.0.11'; // min value for IP
public function getIntegerIP(){ // converts IP from string to integer format
return ip2long($this->value);
}
public static function getFreeIPAddress(){
$records = self::findAll(['attribute'=>self::ATTRIBUTE_DEFAULT_IP_ADDRESS]); // gets all record which contain IP address
$existIPs = ArrayHelper::getColumn($records,'integerIP'); // gets array of IP which is converted to integer by method getIntegerIP
$intIpAddressMin = ip2long(self::IP_ADDRESS_MIN); // gets min IP in integer format
$endRange = empty($existIPs) ? $intIpAddressMin : max($existIPs); // checks if at least one IP is used
$availableIPs = range( $intIpAddressMin, $endRange + 2); // generates array with available IP addresses (+2 because next address can be with last digit 0)
$missingIPs = array_diff($availableIPs,$existIPs); // removes all used IP
foreach ($missingIPs as $value){
$lastDigit = $value % 256;
if ($lastDigit != 0){
return long2ip($value);
}
}
return '';
}
}
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
In my opinion,you can set strict true .
my php code with strict = false
<?php
$y="1800";
$x = array();
for($j=0;$j<50000;$j++){
$x[]= "{$j}";
}
for($i=0;$i<30000;$i++){
if(in_array($y,$x)){
continue;
}
}
time php test.php
real 0m4.418s
user 0m4.404s
sys 0m0.012s
when strict is true
for($i=0;$i<30000;$i++){
if(in_array($y,$x ,true)){
continue;
}
}
time php test.php
real 0m1.548s
user 0m1.540s
sys 0m0.004s
what‘s more ,if you can get the used ip with ascending order . you can get the o(m+n) time complexity,which m is the length of all ip you should try , n is the length of all ip in db with merge algorithm .
if you can get the used ip with ascending order
in Pseudocode .
tmpIp = minIp;
while(temIp <= maxIp){
if( dbIsEmpty){
break;
}
dbIp =getNextFromDb();
while(temIp < dbIp){
printf temIp ;
temIp ++;
}
temIp ++;
}
while(temIp <= maxIp){
printf temIp ;
temIp++;
}
here is my php code, where i repalce echo ip by $count++;
In this demo there is about 80000 ip with type of long
<?php
function mergeSort( $result){
$minIp = ip2long('10.0.0.11') ;
$maxIp = ip2long('10.255.255.255');
$count =0;
$tmpIp = $minIp;
while($temIp <= $maxIp){
if( empty($result)){
break ;
}
$tmp = array_pop($result);
$dbIp =$tmp['ip'];
while($temIp < $dbIp){
// echo temIp ;
// i repalce it by count ++ , i don't want it
//full my teminal .
$count ++;
$temIp ++;
}
$temIp ++;
}
while($temIp <= $maxIp){
//echo $temIp ; replace by $count++
$count ++;
$temIp++;
}
return $count -1;
}
$servername = "localhost";
$username = "root";
$password = "aaaaa";
$dbname = "IP";
$conn = new PDO('mysql:host=' . $servername . ';dbname=' . $dbname , $username, $password);
$conn->setAttribute(PDO::ATTR_AUTOCOMMIT , true);
$stmt = $conn->prepare("select * from ipTable order by ip desc");
$stmt->execute();
$result = $stmt->fetchAll();
$count = mergeSort($result);
echo $count ;
?>
it take about 10s ;
time php test.php
184460881
real 0m10.626s
user 0m10.416s
sys 0m0.168s

Why NodeJS is not so fast in this example?

I heard a lot about how fast NodeJS is. But my simple test case shows, that Apache with PHP is much faster. The codes look like this:
PHP code
require_once("mysqlconnect.php");
$start = round(microtime(true) * 1000);
$r = mysql_query("SELECT field1 FROM mytable");
$arr = array();
while($s = mysql_fetch_array($r)){
$arr[] = $s;
}
$obj = json_encode($arr);
$end = round(microtime(true) * 1000);
echo $end-$start;
NodeJS
var mysql = require('mysql'),
start = new Date().getTime(),
connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'testdb'
}),
json = '',
query = 'SELECT field1 FROM mytable';
connection.connect();
connection.query(query, function(err, results, fields) {
json = JSON.stringify(results);
var elapsed = new Date().getTime() - start;
console.log(elapsed);
connection.end();
});
The table contains 1000 rows and ten tests show that PHP even without any accelerators is at least 3 times faster. Why is that? Does it mean that NodeJS beats PHP only in some special cases?

php code of troubling getting multiple value

I have codes that should be getting value from mysql database, I can get only one value but I have while loop so it can get value and output data separated with comma. But I only get one value and cannot get multiple value. the result should be like this, // End main PHP block. Data looks like this: [ [123456789, 20.9],[1234654321, 22.1] ] here is the code:
<?php
// connect to MySQL
mysql_connect('localhost','','') or die("Can't connect that way!");
#mysql_select_db('temperature1') or die("Unable to select a database called 'temperature'");
if(ISSET($_GET['t']) && (is_numeric($_GET['t'])) ){
// message from the Arduino
$temp = $_GET['t'];
$qry = "INSERT INTO tempArray(timing,temp) VALUES(".time().",'$temp')";
echo $qry;
mysql_query($qry);
mysql_close();
exit('200');
}
// no temp reading has been passed, lets show the chart.
$daysec = 60*60*24; //86,400
$daynow = time();
if(!$_GET['d'] || !is_numeric($_GET['d'])){
$dayoffset = 1;
} else {
$dayoffset = $_GET['d'];
}
$dlimit = $daynow-($daysec*$dayoffset);
$qryd = "SELECT id, timing, temp FROM tempArray WHERE timing>='$dlimit' ORDER BY id ASC LIMIT 1008";
// 1008 is a weeks worth of data,
// assuming 10 min intervals
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
$i=0;
$r = mysql_query($qryd);
$count = mysql_num_rows($r);
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return="[$dt, $te]";
echo $return; //here I get all values [1385435831000, 21][1385435862000, 23][1385435892000, 22][1385435923000, 25][1385435923000, 22]
$i++;
if($i<$count) $return= ","; echo $return; // if there is more data, add a ',' however, it return me ,,,[1385435923000, 22]
$latest = "$dt|$te"; // this will get filled up with each one
}
mysql_close();
// convert $latest to actual date - easier to do it here than in javascript (which I loathe)
$latest = explode('|',$latest);
$latest[0] = date('g:ia, j.m.Y',(($latest[0])/1000)-36000);
?>
You're just assigning $return to the values from the last row your while loop grabbed instead of concatenating it. Try this
$return = "[";
while($row=mysql_fetch_array($r, MYSQL_ASSOC)) {
$tid=$row['id'];
$dt = ($row['timing']+36000)*1000;
$te = $row['temp'];
if($te>$maxtemp) $maxtemp=$te; // so the graph doesnt run along the top
if($te<$mintemp) $mintemp=$te; // or bottom of the axis
$return.="[$dt, $te]";
$i++;
if($i<$count) $return .= ", ";// if there is more data, add a ','
$latest = "$dt|$te"; // this will get filled up with each one
}
$return .= "]";

If the operation is performed if the value in the list I'm looking for

I'm the data with the following code.
$parametre = mysql_query("select * from faturaparametre where musteri='$musteri' and
urungrubu='$urungrubu' and tasimasekli='$tasimasekli' and donem<= '$tarih' and donem2>= '$tarih' and teslimnoktasi='$teslimnoktasi1' and $agirlik BETWEEN min and max");
while($parametresonuc = mysql_fetch_array($parametre)) {
$fatparametreid = $parametresonuc[id];
$ynadresno = $parametresonuc[yuklemenokta];
Skip this procedure if you do not have the following variables: the next one in the list if there is no break in the last one in the search process, how can I do this?
$adresil1 = mysql_query("select * from adresler where id='$yuklemenokta'");
$adressonuc1 = mysql_fetch_array($adresil1);
$yuklemeadresno = $adressonuc1[adresno];
$yuklemeil = $adressonuc1[noktail];
$yuklemeilce = $adressonuc1[noktailce];
$yuklemeilb = "il".$yuklemeil;
This code does not run more than one priority finding. and do not find exactly the same thing
if(eregi($ynadresno, "$yuklemeadresno")) {
$ftid = $fatparametreid;
}elseif(eregi($ynadresno, "$yuklemeilce")) {
$ftid = $fatparametreid;
}elseif(eregi($ynadresno, "$yuklemeilb")) {
$ftid = $fatparametreid;
}else {
}
The array keys should be quoted,
$yuklemeadresno = $adressonuc1['adresno'];
$yuklemeil = $adressonuc1['noktail'];
$yuklemeilce = $adressonuc1['noktailce'];
$yuklemeilb = "il".$yuklemeil;

Categories