Get date and time of max value - php

I have a weather-reading database where I store all data for consumption by a webpage that shows the MAX and MIN pressure.
The problem is that I like to show the time and date in which these values where recorded.
Code I use to read MAX pressure:
$max_out_pressure = mysql_query("SELECT MAX(out_pressure) AS out_pressure FROM $table");
$max_out_pressure = mysql_result($max_out_pressure,0,"out_pressure");
$max_out_pressure = substr($max_out_pressure, 0, 6);
echo "$max_out_pressure";
echo "mbar";
I have the columns ID, Datetime, Pressure, Temperature
Table is named readings
Webpage: http://temperatur.co.nf/readings.php
Never made an database or webpage before, so I`m struggling with this.

This will get the maximum pressure and the date it was recorded.
$sql = "SELECT out_pressure, Datetime
FROM $table
ORDER BY out_pressure DESC
LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$max_out_pressure = $row['out_pressure'];
$max_date = $row['Datetime'];

Related

Having trouble with MySQL double to date conversion

I have searched and searched for ways to do this but have found very limited information.
I have a MySQL table 'msgdb' that contains a field 'ttime' that is in the format double(25,8) (example row = 1352899856.95249200).
I need to routinely cleanup the table by removing any rows where the field 'ttime' is <= today's date -5 days.
These are the only two lines of code I could find related to double to time conversion but cannot get either to work.
SELECT ADDDATE(ADDDATE(ADDDATE('1899-12-31 00:00:00',FLOOR(ttime)), INTERVAL -1 DAY),INTERVAL(MOD(ttime,1)*86400)SECOND) AS TrueDate FROM msgdb
select date('1899-12-31 00:00:00'+ INTERVAL ttime * 24*3600 SECOND) as date from msgdb
I have tried first to display any rows that match the criteria using the code below, before I started using DELETE FROM to make sure I'm getting the correct results.
$query = "select date('1899-12-31 00:00:00'+ INTERVAL ttime * 24*3600 SECOND) as date from msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo $row['date'];
echo '<br>';
}
and also
$query = "SELECT ADDDATE(ADDDATE(ADDDATE('1899-12-31 00:00:00',FLOOR(ttime)), INTERVAL -1 DAY),INTERVAL(MOD(ttime,1)*86400)SECOND) AS TrueDate FROM msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo $row['TrueDate'];
echo '<br>';
}
but both are returning nothing.
UPDATE: Ok so by using this code:
$query = "select ttime from msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo date('m-j-Y, H:i:s', $row[0]);
echo '<br>';
}
I am able to see it convert 'ttime' field from the stored value of 1352899856.95249200 to 11-14-2012, 07:30:56.
So how would I DELETE from the table all rows where ttime is <=now - 5 days?
Figuring out which records have a date before a point in time should be easy:
DELETE FROM table WHERE ttime <= DATE_SUB(NOW(), INTERVAL 5 DAY);
It might also be better to use UTC_TIMESTAMP() if you store all your times in UTC, which is the only sane way to do it.

MySQL Date_Format isn't working with

I have a PHP page with a MySQL database with 2 fields that use the TIME type in MySQL. I want to convert those two fields from the 24 hour format (00:00:00) into 12 hour AM/PM format (00:00 AM) using MySQL's DATE_FORMAT('','') but it's not working.
So far, what I have done is created a 3rd and 4th field that also uses the TIME type. I send the 1st and 2nd field into the 3rd and 4th and convert the 3rd and 4th to preserve the original.
<?php
//connection statements omitted
$sql="SELECT * FROM $table ORDER BY date LIMIT $start, $amount";
$result = $mysqli->query($sql);
//Sends the original time_in data to the new format_in column.
$sql2="UPDATE $table SET format_in = time_in";
$result2=$mysqli->query($sql2);
$sql3="SELECT DATE_FORMAT(format_in,'%l:%i %p') FROM $table";
$result3=$mysqli->query($sql3);
while($row = $result->fetch_array()){
?>
//other fields omitted
<td><?php echo $row['format_in'];?></td>
//end while loop
<?php } ?>
The only thing this code does is replicates whatever was in the time_in column. Which is the standard 24 hour format 00:00:00. Basically, this code doesn't do anything. What am I doing wrong here?
EDITED to show my $result
while($row = $result3->fetch_array()){
instead of
while($row = $result->fetch_array()){
Based on the conversation we had in comments section:
Change
$sql="SELECT * FROM $table ORDER BY date LIMIT $start, $amount";
$result = $mysqli->query($sql);
to
$sql="SELECT field_1,field_2,field_n,DATE_FORMAT(format_in,'%l:%i %p') format_in FROM $table ORDER BY date LIMIT $start, $amount";
$result = $mysqli->query($sql);

Rolling Average Efficiency, php mysql

This script uses php and mysql to compute a one minute rolling average to reduce the impact of outliers on the my data (one minute = 6 10-second rows). It computes everything correctly, but is not efficient enough to do more than 150 rows at a time. I'd like to do as many rows as I can at a time, possibly between 5-10,000 as my table is over 150,000 and I input approximately 8,000 rows per day.
Does anyone have any suggestions as to how I can make this script run more efficiently?
Thanks!
<?php
//connect to database
mysql_connect("localhost","user","password");//database connection
mysql_select_db("database");
$result = mysql_query("SELECT Timestamp FROM table");
if (!$result) {
die('Could not query:' . mysql_error());
}
//get number of rows in table
$resultA = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
echo "There are $num_rows rows.</br>";
//select column to be averaged
$resultB = mysql_query("SELECT PortRPMSignal FROM table");
if (!$resultB) {
die('Could not query:' . mysql_error());
}
//set start equal to the first row you want to calculate the averages from, likely the first null row
$start = 5;
//calculate 1 minute average, the average is correct
for($i = $start; $i<$num_rows; $i++){
$output = mysql_result($result,$i);
$test = mysql_result($resultB,$i)+mysql_result($resultB,$i-1)+mysql_result($resultB,$i-2)+mysql_result($resultB,$i-3)+mysql_result($resultB,$i-4)+mysql_result($resultB,$i-5);
$test2 = $test/6;
$round = round($test2,4);
$temp = mysql_query("SELECT Timestamp FROM table");
if(!$temp){
die('Could not query:' . mysql_error());
}
//gets timestamp at row $i, and inserts new average value into that row in RPMAve column
$time = mysql_result($result,$i);
mysql_query("UPDATE table SET PortMinuteAveRPM = $round WHERE Timestamp = '$time'");
}
For starters, the initial "count" block here can be cleaned up by adding the COUNT() aggregate:
$resultA = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
echo "There are $num_rows rows.</br>";
Change to:
$resultA = mysql_query("SELECT COUNT(*) FROM table");
$row = mysql_fetch_array($result);
$num_rows = $row[0];
echo "There are $num_rows rows.</br>";
That should speed things up considerably on its own. Without it, you're selecting all of the data from the table - a query that will only grow slower the more you put into the table.
For the averages you're computing, is there any logic required that can't be accomplished directly in a MySQL query? Something such as:
UPDATE table SET PortMinuteAveRPM=(SELECT AVG(PortRPMSignal) FROM table WHERE Timestamp BETWEEN '$startTime' AND '$endTime') WHERE TimeStamp='$endTime'
This may save you from looping through results, if it's plausible.
It sounds like you're trying to calculate an autoregressive moving average (ARMA) but there's numerous issues with your interpretation of your data and how you are capturing it.
If you've got a complete set of data (though your question implies that you don't), then work out what time interval contains the required amount of records and get it direct from the database, e.g.
SELECT a.timestamp as base, AVG(b.PortRPMSignal)
FROM table a, table b
WHERE b.timestamp BETWEEN a.timestamp AND a.timestamp+INTERVAL 6 HOUR
GROUP BY a.timestamp
If you want to thin out the datapoints, then try something like....
SELECT a.timestamp as base, AVG(b.PortRPMSignal)
FROM table a, table b
WHERE b.timestamp BETWEEN a.timestamp AND a.timestamp+INTERVAL 6 HOUR
AND DATE_FORMAT(a.timestamp, '%i%s')='0000'
GROUP BY a.timestamp
Although a better solution if you've not got a complete dataset but there's only a small amount of jitter would be to use the modulus of an auto-increment id to pick out fewer rows from 'a'
It's only a start, but you can bin this bit
//get number of rows in table
$resultA = mysql_query("SELECT * FROM table");
$num_rows = mysql_num_rows($result);
echo "There are $num_rows rows.</br>";
Because the following line
$resultB = mysql_query("SELECT PortRPMSignal FROM table");
...will give you a result set that you can use mysql_num_rows on.
Using the * in a query increases the load on the database.
In your for loop you then have this
$temp = mysql_query("SELECT Timestamp FROM table");
if(!$temp){
die('Could not query:' . mysql_error());
}
which means this query runs every time you loop and you're not even using the results.
I don't know if mysqli will give you better performance, but you should use it.

Get total number of records for a given day in Highcharts and PHP

I'm trying to get my highcharts chart working and I'm almost there.. I just have one little problem: I need that the value will be the total count of the records at the same day but I'm kinda confused with my code now and the chart is totally messed up..
Here is the code that pulls the data:
<?php
header("Content-type: text/json");
include('../includes/config.php');
$tablename = "analytics";
$result = mysql_query("SELECT COUNT(*) AS count FROM $tablename");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$sql = "SELECT id, date FROM $tablename ORDER BY date";
$result = mysql_query( $sql ) or die("Couldn't execute query.".mysql_error());
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row['id'] = (int) $row['id'];
$rows[$i] = array(strtotime($row['date'])*1000, $row['id']);
$i++;
}
echo json_encode($rows);
?>
If it will help here is my database values:
insert into `analytics`(`id`,`user`,`item`,`ip`,`country`,`date`) values
(10,1,1,'127.0.0.1','','2011-12-17 06:41:51'),
(11,1,1,'127.0.0.1','','2011-12-17 06:42:23'),
(12,1,1,'127.0.0.1','','2011-12-17 06:43:07'),
(13,1,1,'127.0.0.1','','2011-12-17 06:44:19'),
(14,1,1,'127.0.0.1','','2011-12-17 06:44:21'),
(15,1,1,'127.0.0.1','','2011-12-17 06:44:22'),
(16,1,1,'127.0.0.1','','2011-12-17 06:44:49'),
(17,1,1,'127.0.0.1','','2011-12-17 06:46:59'),
(18,1,1,'127.0.0.1','','2011-12-17 06:47:20'),
(19,1,1,'127.0.0.1','','2011-12-17 06:47:35'),
(20,1,1,'127.0.0.1','','2011-12-17 06:47:42'),
(21,1,1,'127.0.0.1','','2011-12-17 06:48:07'),
(22,1,1,'127.0.0.1','','2011-12-17 06:48:14'),
(23,1,1,'127.0.0.1','','2011-12-17 06:48:29'),
(24,1,1,'127.0.0.1','','2011-12-18 06:49:10'),
(25,1,1,'127.0.0.1','','2011-12-19 07:05:45'),
(26,1,1,'127.0.0.1','','2011-12-20 08:11:32'),
(27,1,1,'127.0.0.1','','2011-12-21 08:26:45'),
(28,1,1,'127.0.0.1','','2011-12-17 08:44:34');
And here is the final result:
I totally lost my self here, can someone help?
EDIT: did what #ajreal said and here is the output:
This is the query to get count for each date
SELECT date, COUNT(*) AS count
FROM $tablename
GROUP BY date;
You can use this query to replace your first query.
And to a loop (like your second query), set $total += $row["count"] to get a grand total like your original first query does

Php/MySQL help - random daily pick?

I'm trying to get a pick from my DB that would last for a day (daily pick). I use the following code:
$query = 'SELECT * FROM table ORDER BY rand() LIMIT 1
But as you can see it only gives me a random pick from the table, and every time I refresh the page it gets me a new random pick. How can I make the pick to last for a whole day?
Thanks in advance <3
I'm trying this:
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
But I get the following error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource. This is the part that gets broken:
$results = mysql_query($query);
while($line = mysql_fetch_assoc($results))
So... it should look like this, right? (I mean, choosing the daily random pick?)
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
I'm trying this now:
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
However, it gets me a mistake that I'm using the 'has' function on a non-object.
If you set the SEED for the rand to an integer value that changes daily, that would solve your problem
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
Would do the trick.
A sane means of doing this would be to automatically generate the pick of the day content via a cron job that was setup to run once a day.
As such, the cron job would execute the SQL you provided and store the appropriate content in a flat file/database table, etc. (or perhaps even just store the choosen id in another table for future lookup purposes).
You can try something like this:
$total = 'SELECT COUNT(*) FROM table;';
$query = 'SELECT * FROM table ORDER BY id ASC LIMIT 1 OFFSET ' . (date('Ymd') % $total) . ';';
I think you'll need to update the random picked record with "today" field = 1..
Something like this:
// ------------
// Run this 3 commands once a day
// Reset all records
mysql_query("UPDATE `table` SET `today` = 0");
// Pick one
$sql = mysql_query("SELECT `id` FROM `table` ORDER BY RAND() LIMIT 1");
$id = mysql_result($sql, 0, 'id');
// Update the record
mysql_query("UPDATE `table` SET `today` = 1 WHERE `id` = {$id}");
// ------------
// Now you can find again your "random found record":
$query = mysql_query("SELECT * FROM `table` WHERE `today` = 1");

Categories