PHP request is too long - php

I am new to php and SQL.
I have a database with 45 000 rows, I need to extract all 'udid' attribute, so there is a lot of data. I put the result in an array, for each udid, I check if udid.xml exists, if the file exist i open it and search for some data, then i reorder the array..While this process I get a timeout error, when I call my script or a 504 error from my internet provider.
Here is my php code :
include("myFunctions.php");
header('Content-type: application/json; charset=utf-8');
$handle = fopen('php://input','r');
// ----------
set_time_limit (0);
$req_Push = $db->sql_query("SELECT * FROM utilisateurs");
echo("COUNT = " .$db->sql_numrows($req_Push). "");
$arrayBigTbl = array();
while ($row_Push = $db->sql_fetchrow($req_Push)){ // while udid ref fichier utilisateurs
$idUser = $row_Push['udid'];
$arrayBigTbl []= $idUser;
}
//print_r($arrayBigTbl);
echo("</br>Count array global = " .count($arrayBigTbl). "--");
$arrayBigTbl = array_unique($arrayBigTbl);
echo("</br>Count array global nettoyée = " .count($arrayBigTbl). " -- Fin2");
$arrayXMLDevice = array();
for ($i = 0; $i < count($arrayBigTbl) ; $i++)
{
if (deviceXMLExist($arrayBigTbl[$i]))
{
$UDIDFile = simplexml_load_file("./UDID/".$arrayBigTbl[$i].".xml");
foreach($UDIDFile->UDID as $item)
{
$valueTemp = $item->valueUDID;
$strig = "" .$valueTemp. "";
$arrayXMLDevice[] = $strig;
}
}
}
//print_r($arrayXMLDevice);
echo("COUNT ARRAY DEVICE XML = " .count($arrayXMLDevice). " --- Fin 3");
$arrayXMLDevice = array_unique($arrayXMLDevice);
echo("COUNT ARRAY DEVICE XML = " .count($arrayXMLDevice). " --- Fin 3");
$arrayXMLDevice = array_values($arrayXMLDevice);
$arraymerge = array_merge ( $arrayBigTbl,$arrayXMLDevice );
echo("COUNT ARRAY MERGE = " .count($arraymerge). " --- </br>");
$arraymerge = array_unique($arraymerge);
echo("COUNT ARRAY MERGE NETTOYEE = " .count($arraymerge). " --- Fin 3");
$arrayFinalPush = array();
for ($i = 0; i < count($arraymerge);$i=$i+1)
{
$aValue = $arraymerge[i];
if(ctype_xdigit($deviceToken) && strlen($deviceToken)>60)
{
$arrayFinalPush[] = $aValue;
}
}
echo("COUNT ARRAY FINAL = " .count($arrayFinalPush). " ---");
How can I resolve this problem so my request gets finished?

I am not at all surprised you get a timeout error you are doing things very inefficiently.
That being said one trick I use with php is to flush the output buffer: How to flush output after each `echo` call?
If you flush the output buffer after each echo then it will give the browser some data and stop it from timing out.
The reason I say it is inefficient is because you generally want to do as much "work" as possible with SQL - things like uniqueness, sorting ordering etc. should be done in SQL rather than PHP whenever possible because SQL is built for it.

Related

PHP for loop with Database and API Data only calculates 1 result

I try to loop trough a php script to calculate a Total Holding of a Persons Portfolio. But my code only puts out one calculated field instead of all from the Database.
My DB looks like this:
id email amount currency date_when_bought price_when_bought
33 test#test.com 100 BTC 2019-04-17 4000
34 test#test.com 50 ETH 2019-04-17 150
My Code (pretty messy)
<?php
include('databasecon.php');
//// GET API JSON DATA
$coinData = json_decode(file_get_contents('https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,ETH,XRB,IOTA,XRP,XLM,TRX,LINK,USDT&tsyms=USD'), true);
//SELECT ALL MAIL
$result = mysqli_query($con, "SELECT DISTINCT email FROM user_data");
$email_array = array();
while($row = mysqli_fetch_array($result))
{
$email_array[] = $row['email'];
};
// PORTFOLIO ARRAYS
for ($i = 0; $i < sizeof($email_array); $i++) {
$sql = mysqli_query($con, "SELECT DISTINCT * FROM crypto_data WHERE email = '$email_array[$i]'");
while($row = mysqli_fetch_array($sql)){
$myCoins[$row['currency']] = array('balance' => $row['amount'],
'boughtprice' => $row['price_when_bought']);
};
// 0 VALUES FOR CALCULATION
$portfolioValue = 0;
$totalNET = 0;
$Value24H = 0;
// information in json path ['RAW'] so safeguard here to be sure it exists
if (isset($coinData['RAW'])) {
// then loop on all entries $cryptoSymbol will contain for example BTC and cryptoInfo the array USD => [...]
foreach($coinData['RAW'] as $cryptoSymbol => $cryptoInfo) {
// safeguard, check path [USD][FROMSYMBOL] exists
if (!isset($cryptoInfo['USD']) || !isset($cryptoInfo['USD']['FROMSYMBOL'])) {
// log or do whatever to handle error here
echo "no path [USD][FROMSYMBOL] found for crypto: " . $cryptoSymbol . PHP_EOL;
continue;
}
// Symbol in on your json path/array [USD][FROMSYMBOL]
$thisCoinSymbol = $cryptoInfo['USD']['FROMSYMBOL'];
$coinHeld = array_key_exists($thisCoinSymbol, $myCoins);
// Only retour held
if ( !$coinHeld ) { continue; }
// get price:
$thisCoinPrice = $cryptoInfo['USD']['PRICE'];
// get symbol holding:
if ($coinHeld) {
$myBalance_units = $myCoins[$thisCoinSymbol]['balance'];
};
// calculate total holdings:
if ($coinHeld) {
$myBalance_USD = $myBalance_units * $thisCoinPrice;
$portfolioValue += $myBalance_USD;
};
echo '<br>';
echo $email_array[$i];
echo $portfolioValue . PHP_EOL;
echo '<br>';
echo '<br>';
$myCoins = null;
}}};
?>
The Steps are:
1 API connection
2 Select Mail adresses from user_data and put them into an Array
3 start for-loop with size of the email_array
4 Query the crypto_data DB to get all results from that mail
5 Put all Data from crypto_data into Array
6 foreach loop the API
7 Calculations
8 Echo the results
9 null $myCoins
As a result, I get the right Mail Adress + the second row (id 33) calculated with the actual price. But my Result should also plus count id 33 and 34 to get the total result.
To clearify, I get "100 * Price of BTC" , but I need "100 * Price of BTC + 50 * Price of ETH"
Somehow my code only puts out 1 row, but does not calculate them like I want to do so here:
// calculate total holdings:
if ($coinHeld) {
$myBalance_USD = $myBalance_units * $thisCoinPrice;
$portfolioValue += $myBalance_USD;
};
Any help is appreciated, thank you very much.
There are few bugs in your code, such as:
You are setting $myCoins to null immediately after the first iteration of foreach loop, so array_key_exists() function will fail in the next iteration. Remove it entirely, there's no need of setting $myCoins to null.
Keep the below just inside the outer for loop. You should not print the portfolio value for each iteration of foreach loop, rather print the aggregated portfolio value for each email address.
echo '<br>';
echo $email_array[$i];
echo $portfolioValue . PHP_EOL;
echo '<br>';
echo '<br>';
Reset $portfolioValue value to 0 at the end of the for loop.
So your code should be like this:
<?php
include('databasecon.php');
// GET API JSON DATA
$coinData = json_decode(file_get_contents('https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,ETH,XRB,IOTA,XRP,XLM,TRX,LINK,USDT&tsyms=USD'), true);
//SELECT ALL MAIL
$result = mysqli_query($con, "SELECT DISTINCT email FROM user_data");
$email_array = array();
while($row = mysqli_fetch_array($result)){
$email_array[] = $row['email'];
}
// PORTFOLIO ARRAYS
for ($i = 0; $i < sizeof($email_array); $i++) {
$sql = mysqli_query($con, "SELECT DISTINCT * FROM crypto_data WHERE email = '$email_array[$i]'");
while($row = mysqli_fetch_array($sql)){
$myCoins[$row['currency']] = array('balance' => $row['amount'], 'boughtprice' => $row['price_when_bought']);
}
// 0 VALUES FOR CALCULATION
$portfolioValue = 0;
$totalNET = 0;
$Value24H = 0;
// information in json path ['RAW'] so safeguard here to be sure it exists
if (isset($coinData['RAW'])) {
// then loop on all entries $cryptoSymbol will contain for example BTC and cryptoInfo the array USD => [...]
foreach($coinData['RAW'] as $cryptoSymbol => $cryptoInfo) {
// safeguard, check path [USD][FROMSYMBOL] exists
if (!isset($cryptoInfo['USD']) || !isset($cryptoInfo['USD']['FROMSYMBOL'])) {
// log or do whatever to handle error here
echo "no path [USD][FROMSYMBOL] found for crypto: " . $cryptoSymbol . PHP_EOL;
continue;
}
// Symbol in on your json path/array [USD][FROMSYMBOL]
$thisCoinSymbol = $cryptoInfo['USD']['FROMSYMBOL'];
$coinHeld = array_key_exists($thisCoinSymbol, $myCoins);
// Only retour held
if ( !$coinHeld ) { continue; }
// get price:
$thisCoinPrice = $cryptoInfo['USD']['PRICE'];
// get symbol holding:
if ($coinHeld) {
$myBalance_units = $myCoins[$thisCoinSymbol]['balance'];
}
// calculate total holdings:
if ($coinHeld) {
$myBalance_USD = $myBalance_units * $thisCoinPrice;
$portfolioValue += $myBalance_USD;
}
}
}
echo '<br>';
echo $email_array[$i];
echo $portfolioValue . PHP_EOL;
echo '<br>';
echo '<br>';
$portfolioValue = 0;
}
?>
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.

Is there a way to run PHP long loop code faster?

I have a code that runs a query on an external (slow) API and loops through a lot of variables and inserts data, sends email, ect'.
This is the main function as an example:
// MAIN: Cron Job Function
public function kas_alert() {
// 0. Deletes all the saved data from the `data` table 1 month+ ago.
// $this->kas_model->clean_old_rows();
// 1. Get 'prod' table
$data['table'] = $this->kas_model->prod_table();
// 2. Go through each row -
foreach ( $data['table'] as $row ) {
// 2.2. Gets all vars from the first query.
$last_row_query = $this->kas_model->get_last_row_of_tag($row->tag_id);
$last_row = $last_row_query[0];
$l_aaa_id = $last_row->prod_aaa_id;
$l_and_id = $last_row->prod_bbb_id;
$l_r_aaa = $last_row->dat_data1_aaa;
$l_r_and = $last_row->dat_data1_bbb;
$l_t_aaa = $last_row->dat_data2_aaa;
$l_t_and = $last_row->dat_data2_bbb;
$tagword = $last_row->tag_word;
$tag_id = $last_row->tag_id;
$country = $last_row->kay_country;
$email = $last_row->u_email;
$prod_name = $last_row->prod_name;
// For the Weekly report:
$prod_id = $last_row->prod_id;
$today = date('Y-m-d');
// 2.3. Run the tagword query again for today on each one of the tags and insert to DB.
if ( ($l_aaa_id != 0) || ( !empty($l_aaa_id) ) ) {
$aaa_data_today = $this->get_data1_aaa_by_id_and_kw($l_aaa_id, $tagword, $country);
} else{
$aaa_data_today['data1'] = 0;
$aaa_data_today['data2'] = 0;
$aaa_data_today['data3'] = 0;
}
if ( ($l_and_id != 0) || ( !empty($l_and_id) ) ) {
$bbb_data_today = $this->get_data1_bbb_by_id_and_kw($l_and_id, $tagword, $country);
} else {
$bbb_data_today['data1'] = 0;
$bbb_data_today['data2'] = 0;
$bbb_data_today['data3'] = 0;
}
// 2.4. Insert the new variables to the "data" table.
if ($this->kas_model->insert_new_tag_to_db( $tag_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $aaa_data_today['data2'], $bbb_data_today['data2'], $aaa_data_today['data3'], $bbb_data_today['data3']) ){
}
// Kas Alert Outputs ($SEND is echoed in it's original function)
echo "<h1>prod Name: $prod_id</h1>";
echo "<h2>tag id: $tag_id</h2>";
var_dump($aaa_data_today);
echo "aaa old: ";
echo $l_r_aaa;
echo "<br> aaa new: ";
echo $aaa_data_today['data1'];
var_dump($bbb_data_today);
echo "<br> bbb old: ";
echo $l_r_and;
echo "<br> bbb new: ";
echo $bbb_data_today['data1'];
// 2.5. Check if there is a need to send something
$send = $this->check_if_send($l_aaa_id, $l_and_id, $l_r_aaa, $aaa_data_today['data1'], $l_r_and, $bbb_data_today['data1']);
// 2.6. If there is a trigger, send the email!
if ($send) {
$this->send_mail($l_aaa_id, $l_and_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $l_r_aaa, $l_r_and, $tagword, $email, $prod_name);
}
}
}
This CodeIgniter controller is runs every day and I get this running (Cronjob) for too long using almost nothing from the CPU and RAM (RAM is at 400M/4.25G and CPU at ONLY 0.7%-1.3%).
I wonder if there's an option to split all foreach loops to smaller threads (and I'm not sure if forking will do here) and run all the foreach loops in parallel but in a way that it wont get my server crashing.
I'm no DevOps and really interested learning - What should I do in this case?

PHP+Apache2+Ubuntu Server: How to get all threads to work in parallel?

I usually work with web hosting companies but I decided to start learning working with servers to expand my knowledge.
I'll better give a real example to explain my question the best:
I have a web application that gathers data from a slow API that returns JSON data of products.
I have a function running every 1AM running a lot of queries on "id"s in my database.
Crontab:
0 1 * * * cd /var/www/html/tools; php index.php aso Cli_kas kas_alert
So this creates a process for the app (please correct me here if I'm wrong) and each process creates threads, and just to be more accurate, they are multi-threads since they do more than one thing: like pulling data from the DB to get the right variables and string them to the API queries, getting the data from the API, organizing it, searching the relevant data, and then inserting new data to the database.
The main PHP functions:
// MAIN: Cron Job Function
public function kas_alert() {
// 0. Deletes all the saved data from the `data` table 1 month+ ago.
// $this->kas_model->clean_old_rows();
// 1. Get 'prod' table
$data['table'] = $this->kas_model->prod_table();
// 2. Go through each row -
foreach ( $data['table'] as $row ) {
// 2.2. Gets all vars from the first query.
$last_row_query = $this->kas_model->get_last_row_of_tag($row->tag_id);
$last_row = $last_row_query[0];
$l_aaa_id = $last_row->prod_aaa_id;
$l_and_id = $last_row->prod_bbb_id;
$l_r_aaa = $last_row->dat_data1_aaa;
$l_r_and = $last_row->dat_data1_bbb;
$l_t_aaa = $last_row->dat_data2_aaa;
$l_t_and = $last_row->dat_data2_bbb;
$tagword = $last_row->tag_word;
$tag_id = $last_row->tag_id;
$country = $last_row->kay_country;
$email = $last_row->u_email;
$prod_name = $last_row->prod_name;
// For the Weekly report:
$prod_id = $last_row->prod_id;
$today = date('Y-m-d');
// 2.3. Run the tagword query again for today on each one of the tags and insert to DB.
if ( ($l_aaa_id != 0) || ( !empty($l_aaa_id) ) ) {
$aaa_data_today = $this->get_data1_aaa_by_id_and_kw($l_aaa_id, $tagword, $country);
} else{
$aaa_data_today['data1'] = 0;
$aaa_data_today['data2'] = 0;
$aaa_data_today['data3'] = 0;
}
if ( ($l_and_id != 0) || ( !empty($l_and_id) ) ) {
$bbb_data_today = $this->get_data1_bbb_by_id_and_kw($l_and_id, $tagword, $country);
} else {
$bbb_data_today['data1'] = 0;
$bbb_data_today['data2'] = 0;
$bbb_data_today['data3'] = 0;
}
// 2.4. Insert the new variables to the "data" table.
if ($this->kas_model->insert_new_tag_to_db( $tag_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $aaa_data_today['data2'], $bbb_data_today['data2'], $aaa_data_today['data3'], $bbb_data_today['data3']) ){
}
// Kas Alert Outputs ($SEND is echoed in it's original function)
echo "<h1>prod Name: $prod_id</h1>";
echo "<h2>tag id: $tag_id</h2>";
var_dump($aaa_data_today);
echo "aaa old: ";
echo $l_r_aaa;
echo "<br> aaa new: ";
echo $aaa_data_today['data1'];
var_dump($bbb_data_today);
echo "<br> bbb old: ";
echo $l_r_and;
echo "<br> bbb new: ";
echo $bbb_data_today['data1'];
// 2.5. Check if there is a need to send something
$send = $this->check_if_send($l_aaa_id, $l_and_id, $l_r_aaa, $aaa_data_today['data1'], $l_r_and, $bbb_data_today['data1']);
// 2.6. If there is a trigger, send the email!
if ($send) {
$this->send_mail($l_aaa_id, $l_and_id, $aaa_data_today['data1'], $bbb_data_today['data1'], $l_r_aaa, $l_r_and, $tagword, $email, $prod_name);
}
}
}
For #Raptor, this is the function that get's the API data:
// aaa tag Query
// Gets aaa prod dataing by ID.
public function get_data_aaa_by_id_and_tg($id, $tag, $query_country){
$tag_for_url = rawurlencode($tag);
$found = FALSE;
$i = 0;
$data = array();
// Create a stream for Json. That's how the code knows what to expect to get.
$context_opts = array(
'http' => array(
'method' => "GET",
'header' => "Accepts: application/json\r\n"
));
$context = stream_context_create($context_opts);
while ($found == FALSE) {
// aaa Query
$json_query_aaa = "https://api.example.com:443/aaa/ajax/research_tag?app_id=$id&term=$tag_for_url&page_index=$i&country=$query_country&auth_token=666";
// Get the Json
$json_query_aaa = file_get_contents($json_query_aaa, false, $context);
// Turn Json to a PHP array
$json_query_aaa = json_decode($json_query_aaa, true);
// Get the data2
$data2 = $json_query_aaa['tag']['data2'];
if (is_null($data2)){ $data2 = 0; }
// Get data3
$data3 = $json_query_aaa['tag']['phone_prod']['data3'];
if (is_null($data3)){ $data3 = 0; }
// Finally, the main prod array.
$json_query_aaa = $json_query_aaa['tag']['phone_prod']['app_list'];
if ( count($json_query_aaa) > 2 ) {
for ( $j=0; $j<count($json_query_aaa); $j++ ) {
if ( $json_query_aaa[$j]['id'] == $id ) {
$found = TRUE;
$data = $json_query_aaa[$j]['data'] + 1;
break;
}
if ($found == TRUE){
break;
}
}
$i++;
} else {
$data = 0;
break;
}
}
$data['data1'] = $data;
$data['data2'] = $data2;
$data['data3'] = $data3;
return $data;
}
All threads are stacked one after an other, and when one thread is done, only then - the second thread can proceed, ect'.
And in technical view on this, all threads wait in the RAM until the one before them is done working "inside" the CPU. (correct me if I'm wrong again :] )
This doesn't even "tickle" the servers RAM or CPU when looking at it in the process manager (I use "htop"). RAM is at 400M/4.25G and CPU at ONLY 0.7%-1.3%.
Making me feel this isn't the best I can get from my current server, and getting slow results from my web app.
How do I get things done in a way that all threads work in parallel, but not to a point that my app crashes due to lacks of CPU or RAM?

Eliminating HTML escape sequences from string with PHP

I am working on a php script to pull quest data from wowhead, particularly what starts and ends the quest, whether it is an item or a npc, and what its id or name is, respectively. This is the relevant portion of the whole script, with the rest involving database insertion. This is the completed snippet of code I came up with if anyone is interested. Also, seeing as this will run about 15,000 times, is this the best method of obtaining/storing the data?
<?php
$quests = array();
//$questlimit = 14987;
$questlimit = 5;
$currentquest = 1;
$questsprocessed = 0;
while($questsprocessed != $questlimit)
{
echo "<br>";
echo " Start of iteration: ".$questsprocessed." ";
echo "<br>";
echo " Attempting to process quest: ".$currentquest." ";
echo "<br>";
$quests[$currentquest] = array();
$baseurl = 'http://wowhead.com/quest=';
$fullurl = $baseurl.$currentquest;
$data = drupal_http_request($fullurl);
$queststartloc1 = strpos($data->data, 'quest_start');
$queststartloc2 = strpos($data->data, 'quest_end');
if($queststartloc1==false)
{$currentquest++; echo "No data for this quest"; echo "<br>"; continue;}
$questendloc1 = strpos($data->data, 'quest_end');
$questendloc2 = strpos($data->data, 'x5DDifficulty');
$startcaptureLength = $queststartloc2 - $queststartloc1;
$endcaptureLength = $questendloc2 - $questendloc1;
$quest_start_raw = substr($data->data,$queststartloc1, $startcaptureLength);
$quest_end_raw = substr($data->data, $questendloc1, $endcaptureLength);
$startDecoded = preg_replace('~\\\\x([A-Fa-f0-9]{2})~e', 'chr("0x$1")', $quest_start_raw);
$endDecoded = preg_replace('~\\\\x([A-Fa-f0-9]{2})~e', 'chr("0x$1")', $quest_end_raw);
$quests[$currentquest]['Start'] = array();
$quests[$currentquest]['End'] = array();
if(strstr($startDecoded, 'npc'))
{
$quests[$currentquest]['Start']['Type'] = "npc";
preg_match('~npc=(\d+)~', $startDecoded, $startmatch);
}
else
{
$quests[$currentquest]['Start']['Type'] = "item";
preg_match('~item=(\d+)~', $startDecoded, $startmatch);
}
$quests[$currentquest]['Start']['ID'] = $startmatch[1];
if(strstr($endDecoded, 'npc'))
{
$quests[$currentquest]['End']['Type'] = "npc";
preg_match('~npc=(\d+)~', $endDecoded, $endmatch);
}
else
{
$quests[$currentquest]['End']['Type'] = "item";
preg_match('~item=(\d+)~', $endDecoded, $endmatch);
}
$quests[$currentquest]['End']['ID'] = $endmatch[1];
//var_dump($quests[$currentquest]);
echo " End of iteration: ".$questsprocessed." ";
echo "<br>";
echo " Processed quest: ".$currentquest." ";
echo "<br>";
$currentquest++;
$questsprocessed++;
}
?>
These are called "escape sequences". Normally, they're used to represent characters not printable otherwise, but can encode any character. In php, you can decode them like this:
$text = '
quest_start\\x5DStart\\x3A\\x20\\x5Bitem\\x3D16305\\x5D\\x5B\\x2Ficon\\x5D\\x5B\\x2Fli\\x5D\\x5Bli\\x5D\\x5Bicon\\x20name\\x3Dquest_end\\x5DEnd\\x3A\\x20\\x5Burl\\x3D\\x2Fnpc\\x3D12696\\x5DSenani\\x20Thunderheart\\x5B\\x2Furl\\x5D\\x5B\\x2Ficon\\x5D\\x5B\\x2Fli\\x5D\\x5Bli\\x5DNot\\x20sharable\\x5B\\x2Fli\\x5D\\x5Bli
';
$decoded = preg_replace('~\\\\x([A-Fa-f0-9]{2})~e', 'chr("0x$1")', $text);
Which gives you a string similar to this:
quest_start]Start: [item=16305][/icon][/li][li][icon name=quest_end]End: [url=/npc=12696]Senani Thunderheart[/url][/icon][/li][li]Not sharable[/li][li
(obviously, some kind of BB-code). To remove all bbcodes, yet one replacement is necessary:
$clean = preg_replace('~(\[.+?\])+~', ' ', $decoded);

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 .= "]";

Categories