Having trouble with MySQL double to date conversion - php

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.

Related

How to Subtract current date time from date time in database - PHP

I'm working on a project.I have to check " how many minutes ago ,user updated the database " .For that I used following code :
<?php
include('connect_db.php');
$sql =" SELECT * FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$time = strtotime($row['time_']);
$current=time();
$sub_time=$current-$time;
echo $sub_time;
}
The problem is the code is returning negative values like [ -17173 ].
The date-time stored in my db is like [ 2018-07-14 11:42:21.006515 ]
I simply want to compare current time with the the time stored in database get results in seconds or minutes .
I need help to solve this issue.Thank you .
You can just change your select statement to give you the time difference in seconds as shown below:
$sql =" select UNIX_TIMESTAMP(current_Timestamp()) - UNIX_TIMESTAMP(time_) FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;
I think DateTime is better approach, as it has the methods to achieve the result you need.
maybe something like this:
$time=$row['time_'];
$curr_time=new DateTime();
$difference=$time->diff($curr_time);
http://php.net/manual/en/class.datetime.php
Updated
You should use the DateTime functions to figure out the difference in time. You should be able to integrate this into your code.
I incorporated my suggested code as a function into your original code. This should work for you.
Try this:
function timeDiff($date){
$date = new DateTime(date('Y-m-d H:i:s', strtotime($date)));
$current = new DateTime(date('Y-m-d H:i:s'));
$interval = $date->diff($current);
return $interval->format('%H:%I:%S');
}
include('connect_db.php');
$sql ="SELECT * FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo timeDiff($row['time_']);
}
}
You first need to convert them to timestamp. And them subtract them convert the resuting timestamp back to format you want.
while($row = $result->fetch_assoc()) {
$time = strtotime($row['time_']);
$current=time();
$sub_time=date('d-m-y h:i:s',(strototime(date('d-m-y h:i:s')-$time));
echo $sub_time;
}
You need to handle the greater than and less than cases too.

MySQL SELECT using WHERE as date filter does not work

I am using the following SELECT script which successfully finds the values for $payer_email, reminder_date and sub_expire_date, but no data is being produced when I apply the commented out WHERE condition to the SELECT. The intention of the WHERE is to filter the values from the SELECT to only provide those values which point to the subscription expiry (sub_expire_date) thirty days ahead of time, but no values are derived when the values do exist.
Can anyone tell me why the SELECT fails upon the inclusion of the WHERE?
<?php
error_reporting(E_ALL ^ E_NOTICE);
include_once("../real_conn/real_i_conn.php");
$reminder_date = date("Y-m-d", strtotime("+30 days"));
echo $reminder_date . "<br><br>";
$sql = "SELECT sec_tblpurchased_secureareas.users_id,
sec_tblpurchased_secureareas.sub_expire_date,
DATE_ADD(sec_tblpurchased_secureareas.sub_expire_date, INTERVAL - 30
day) AS reminder_date, sec_tblusers.payer_email
FROM sec_tblpurchased_secureareas
INNER JOIN sec_tblusers ON sec_tblusers.recid =
sec_tblpurchased_secureareas.users_id";
//WHERE DATE_ADD(sec_tblpurchased_secureareas.sub_expire_date, INTERVAL- 30 day) = '". $reminder_date ."' ";
$result = mysqli_query($conni, $sql);
if ($result) {
// Return the number of rows in result set
$rowcount = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $rowcount);
echo "<br><br>";
}
while ($num = mysqli_fetch_array($result)) {
//echo $num;
$payer_email = $num['payer_email'];
echo $num['payer_email'] . " <br>";
$reminder_date = $num['reminder_date'];
$reminder_date = date_create("$reminder_date");
echo date_format($reminder_date, "Y/m/d") . " remind<br>";
$sub_expire_date = $num['sub_expire_date'];
$sub_expire_date = date_create("$sub_expire_date");
echo date_format($sub_expire_date, "Y/m/d") . " expire<br><br>";
}
?>
Your code is very difficult to read, and the code you shared is invalid (the line before the commented out //WHERE line ends "; but the line after starts - 30 -- this absolutely won't compile.
That said, my best guess is that you're using DATE_ADD incorrectly. Check out the documentation on it here: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
Notice it returns a DATETIME, never a DATE. If you wrap it in a DATE() call, however, you might get what you want.
FWIW, I find this easier to read:
SELECT x.users_id
, x.sub_expire_date
, DATE_ADD(x.sub_expire_date, INTERVAL - 30 DAY) reminder_date
, u.payer_email
FROM sec_tblpurchased_secureareas x
JOIN sec_tblusers u
ON u.recid = x.users_id;
I think the problem has been solved, indirectly. It looks like I just had to use
DATE_SUB(sec_tblpurchased_secureareas.sub_expire_date, INTERVAL 30 day) AS reminder_date
instead of DATE_ADD with a negative day value. This give me the variable I need to trigger the CRON.
Thanks for your help.

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);

Compare timestamp with date in php

i have this code which permits me to retrieve all the information in which the timestamp regarding that information is equal to another date.
Here is the code:
$information="SELECT * FROM scheda_anagrafica WHERE FROM_UNIXTIME('time_inserted','%d-%m-%Y') = '" . $giorno_selcted. "'
";
$result1 = mysql_query($information) or die (mysql_error());
while( $row = mysql_fetch_array($result1)) {
echo $row['information1'];
}
giorno_selected prints something like: 25-09-2012
What am i doing wrong here?
Thanks!
first of all, you should not use mysql functions on the left hand side of a operator in a where clause. this way mysql needs to read the complete table on disk to compute the value to compare with instead of optimizing the query for speed and resource usage (IO, cpu).
from your question and comments i understand, that you are querying the database for rows which have the same day as the string in your $giorno_selected represents. so you need to find all rows with timestamps between 0:00 and 23:59 on that specific day:
$giorno_timestamp_start = date_create_from_format('d-m-Y', $giorno_selected)->getTimestamp();
$giorno_timestamp_end = $giorno_timestamp_start + 86399; //add almost all seconds per day onto the start timestamp
$information="SELECT * FROM scheda_anagrafica WHERE time_inserted BETWEEN " . $giorno_timestamp_start. " AND ". $giorno_timestamp_end;
$result1 = mysql_query($information) or die (mysql_error());
while( $row = mysql_fetch_array($result1)) {
echo $row['information1'];
}
this works if your time_inserted column is of type integer and holds unix_timestampds.
if it is of type datetime or timestamp you need to modify the query like this:
$information="SELECT * FROM scheda_anagrafica WHERE time_inserted BETWEEN FROM_UNIXTIME(" . $giorno_timestamp_start. ") AND FROM_UNIXTIME(". $giorno_timestamp_end .")";

strange mysql behaviour on timestamp

Please have a look at this mysql query. What it should do is pretty simple - list dates, created from timestamps not older than 10 days.
It works, but not perfectly ...
If I have only 1 timestamp matching, I have 0 results.
If I have 2 timestamps matching, I have 1 results.
if I have 3 timestamps matching, I have 2 results
... and so on...
So the newest timestamp in the table is always ignored by the query, WHY ?!
$timestamp_now = date('U');
$timestamp_10_day_back = $timestamp_now - 864000;
mysql_select_db("$db_visitors");
$sql = "SELECT DATE(FROM_UNIXTIME(visitors_timestamp))
FROM visitors
WHERE visitors_timestamp > $timestamp_10_day_back
ORDER BY visitors_timestamp DESC";
$sql = mysql_query($sql);
$row = mysql_fetch_array($sql);
while($row = mysql_fetch_array($sql)) {
echo $row[0] . "<br>";
}
Just remove
$row = mysql_fetch_array($sql);
...which is swallowing your first result
First row is being ignored because of the row $row = mysql_fetch_array($sql); then you call it again in your while loop . just remove this row .
try the code following
$n=count($row);
if($n>0){
for($i=0;$i<$n;$i++){
echo $row[i];}}
or
print_r($row);

Categories