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")) {
Related
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.
I get result from first query correctly However, when I want to use them in second query in WHERE condition I get query error 1064. If I remove WHERE it will work fine. Also,when I try to echo variables inside while in second query code it will print.the variables will not work only in WHERE in second query
$queryDate = "SELECT date , time from DATES where ID = $ID";
$result = mysqli_query($connection, $queryDate);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$date = $row['date'];
$time = $row['time'];
}
}
$queryCom = "SELECT * from DATES, BOOKING where dates.time = $time and booking.IDofFullDate= $date";
$result1 = mysqli_query($connection, $queryCom);
if (!$result1)
{
die("Query Faile". mysqli_errno($connection));
}
if ($result1->num_rows >0) {
echo $date;
echo $time;
}
on your second query try this below:
$queryCom = "SELECT * from DATES as dates, BOOKING as booking where dates.time = $time and booking.IDofFullDate= $date";
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
$id = 2;
// query to fetch delayed
$sql = "SELECT * FROM leads WHERE status = ('$id') LIMIT 1";
$obResult = $objConnection->query($sql);
// query to fetch if there is no delayed
$q = "SELECT * FROM leads WHERE status = ('$id') AND later != '1' ORDER BY postnummer LIMIT 1";
$oResult = $objConnection->query($q);
// primary query to run, which makes use of the two above accordingly
$query = "SELECT * FROM leads WHERE status = ('$id') LIMIT 1";
$objResult = $objConnection->query($query);
while ($row = $objResult->fetch_object()) {
if (new DateTime() > $row->delay && $row->delay != '0000-00-00 00:00:00') {
while ($row = $obResult->fetch_object()) {
echo $row->firmanavn;
}
} else {
while ($row = $oResult->fetch_object()) {
echo $row->firmanavn;
}
}
}
Changed my code to this, and still i got the same problem, the if clause if met, but it echoes from my else instead
Reason is that you are using same variable names that overwrite each other. $objResult rename this to something like $objResult2 for the inner query.
One thing to keep in mind is that your inner query inside a loop is really unnecessary unless you did not provide some piece of code. You can just put that query outside of while loop. Will save you time & memory.
Although I think there are other ways this code could be cleaned up, it seems to me that you're attempting to compare a DateTime object to a date string, which is going to yield unpredictable results. Try changing your while part to:
$current_date = new DateTime();
while ($row = $objResult->fetch_object()) {
if (
$current_date->format('Y-m-d H:i:s') > $row->delay &&
$row->delay != '0000-00-00 00:00:00'
) {
while ($row = $obResult->fetch_object()) {
echo $row->firmanavn;
}
} else {
while ($row = $oResult->fetch_object()) {
echo $row->firmanavn;
}
}
}
I'm not sure this will fully solve your issues, but it should get you closer.
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.