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.
Related
I am displaying a list of months and years from the database like this into a drop-down menu:
$stmt = $link->prepare("SELECT `b_date` FROM `summary` GROUP BY YEAR(`b_date`), MONTH(`b_date`)");
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
while($row = $result->fetch_assoc()) {
$month = date('F Y', strtotime($row['b_date']));
echo "<option value='{$month}'>{$month}</option>";
}
}
When the user clicks on a choice, it redirects to another page like:
mypage.com/results.php?date=
The problem is that I don't know what to set the value as. In the current code the url produced looks like:
php?date=April%202017
That obviously isn't ideal. And the point is that on the results page I need to show results for the month that was selected. So, I need that query string to query the database.
You can put to select value something like 05-2017:
while($row = $result->fetch_assoc()) {
$month = date('m-Y', strtotime($row['b_date']));
echo "<option value='{$month}'>{$month}</option>";
}
And then get it with DateTime object:
$date = DateTime::createFromFormat('m-Y', $_GET['date']);
And then you can format this object to any format you want:
$formated_date = $date->format('Y-m-d');
You can chose another format, but I think you understand my idea.
UPD. To execute all record on this month try to use this code:
$date = DateTime::createFromFormat('m-Y', $_GET['date']);
$stmt = $link->prepare("SELECT * FROM `summary` WHERE YEAR(`b_date`) = :year AND MONTH(`b_date`) = :month");
$stmt->bindParam(':month', $date->format('m'));
$stmt->bindParam(':year', $date->format('Y'));
$stmt->execute();
$result = $stmt->get_result();
I think its working but maybe need to fix.
Change like this (use urlencode()):-
$month = date('m-Y', strtotime($row['b_date']));
echo "<option value='".urlencode($month)."'>{$month}</option>";
Now on next page check $_GET['date'] and see it's coming proper or not?
if it come proper in format like m-Y then split it with - and now you get month and year separately. Use them in your query or wherever you want.
Query need to be like something:-
$_GET['date'] = '04-2017';
$date_array = explode('-',$_GET['date']);
$month = $date_array[0];
$year = $date_array[1];
"SELECT * FROM summary WHERE MONTH(<you date column name>) = $month";
U can format data in select (postgres, mysql...)
SELECT TO_CHAR('MM-YYYY', b_date) AS formated_date FROM summary GROUP BY TO_CHAR('MM-YYYY', b_date
I try to take a date and do countdown untill that day like following:
The date i want to countdown to: 2016-05-1 00:00:00
Then i want to calculate the diff between the date and now so i can do countdown timer.
I have this:
date_default_timezone_set("Asia/Jerusalem");
if ($result = $db->query("SELECT TIMESTAMPDIFF(SECOND, NOW(), 2016-05-1 00:00:00)")) {
while($row = $result->fetch_array()) {
$currentTimeLeft= $row['TIMESTAMPDIFF(SECOND, NOW(), 2016-05-1 00:00:00)'];
}
echo json_encode($currentTimeLeft);
}
I dont understand why this returning empty. What is wrong here?
I see quote issue in your query
try this
if($result = $db->query("SELECT TIMESTAMPDIFF(SECOND,NOW(),'2016-05-1 00:00:00') as datediff")) {
while($row = $result->fetch_array()) {
$currentTime = $row['datediff'];
}
echo json_encode($currentTime);
I have added an alias "datediff" to the result column as well
you are missing quotes in the query
if ($result = $db->query("SELECT TIMESTAMPDIFF(SECOND, NOW(), '2016-05-1 00:00:00') as t")) {
I got the following problem. I got a mysql field which is type "text" and there are many birthday dates in it.
I want to print the dates out and sort it in my way of date format. I can't change the type in the database because it's related to some user profile value fields.
The value's thats in the database are such this:
1978-12-31 23:59:59
This is my query:
$result = mysql_query("SELECT a.value, b.username from yrt6h_community_fields_values a join yrt6h_users b on a.user_id = b.id where a.field_id = 3 order by a.value;");
And this my example php file:
<table>
<tr>
<td>User:</td>
<td>Datum:</td>
</tr>
<?php
while($row = mysql_fetch_array($result)){
echo '<tr>';
echo '<td>';
echo $row['username'] . ' : ';
echo '</td>';
echo '<td>';
echo $row['value'];
echo '</td></tr>';
}
?>
</table>
I tried all of the date format functions of mysql, but then i got nothing.
For example I tried this:
mysql_query("SELECT str_to_date(a.value, '%d.%m.%Y'), ...
or
mysql_query("SELECT str_to_date(date_format(a.value, '%Y.%m.%d') %d.%m.%Y), ...
But I do that, the echo of the date is empty. Theres nothing to print out anymore. But why? Even if I put this query directly in the database I got NULL for the birthday value.
why dont you try to do it with php like -
echo date('d-m-Y', strtotime($yourDate));//the first paramete is the date format you want and the second is the value you are getting from database.
Reference for more understanding, example and formats.
Almost there!
I would suggest that you first get the data from the db with
mysql_query("SELECT str_to_date(a.value, '%d.%m.%Y')
Then
while($row = mysql_fetch_array($result))
{
$date = $row['date'];
$time = strtotime($date);
$formattedDate = date('Y-m-d', $time);
}
echo $formattedDate ;
Does that make senese?
Have you tried the PHP Date() function?
You could do something like so:
If you're looking for all records that match a specific date:
$timestamp = date('Y-m-d H:i:s'); //get current timestamp
mysql_query("SELECT * FROM `table` WHERE `timestamp` = '$timestamp'");
Or -- If you're trying to select/order by Timestamp:
mysql_query("SELECT * FROM `table` ORDER BY `timestamp`"); //select all order by timestamp
you can use mysql "cast" function.
rewrite the query in such a way:
"SELECT cast(a.value as DATETIME) new_dob,str_to_date(a.value, '%d.%m.%Y') dob from table_nm where cond"
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.
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);