I need to test current time against a datetime from database, if it has been 30 mins then execute code, if not then dont. This is where I am at and I am stuck:
$link = mysqli_connect("hostname", "username", "password", "database");
$q = "SELECT id FROM dwCache ORDER BY id DESC LIMIT 1";
$qu = mysqli_query($link, $q);
while($row=mysqli_fetch_array($qu, MYSQL_ASSOC)){
$id = $row['id'];
$cache = $row['cache'];
$timest = $row['time'];
}
$newTime =
$difference = $timest
if($timest >= )
As you can see towards the bottom I lose it as I am not sure what to do.
$timest returns : 2013-02-01 12:36:01 as the format Y-m-d h-i-s
Apologies on double post, other deleted.
First convert $timest to timestamp
$time = strtotime($timest);
$curtime = time();
if(($curtime-$time) > 1800) { //1800 seconds
//do stuff
}
do it all in sql statement
SELECT id FROM `dqCache` WHERE `time`<DATE_SUB(NOW(), INTERVAL 30 MINUTE);
This will return everything from your table where the time column is before 30 minutes before now.
I like to use unix timestamps in this situation.
$timest = date('u'); // gets the unix timestamp
$q = "SELECT id
FROM `dwCache`
WHERE {$timest} - UNIX_TIMESTAMP(`timestamp_col`) > 1800";
Explanation:
This basically calculates the difference between the current time and the time in the table column. If it's higher than 1800 (30 minutes), it will select the row, and your PHP code will be executed.
Advantages
There are some advantages to using this instead of the PHP check you started doing. You will select fewer rows, thus occupy less memory.
PS:
Thumbs up for using MySQLi !
SELECT id FROM dwCache ORDER BY id DESC LIMIT 1
you'll get only id field, it's the first.
The second, for time converting: MySQL convert datetime to Unix timestamp
Third: you can convert your time string using strtotime function.
Related
As the title says.
From the database, in the resultset, I want those rows where the date and time (schedule column) are already passed.
In the database I have
On the PHP page I have:
$now = time();
$result = $mysqli->query("SELECT * FROM schedules WHERE $now >= UNIX_TIMESTAMP(schedule)");
However, if I test this on 2015-09-19 at 18:50:00, I get no results at all, while instead I should only get the row with ID 39.
As much as I know I am comparing two valid timestamps - the one generated by time() and the one converted from the database with UNIX_TIMESTAMP() - so what isn't working?
EDIT: I already tried to do
$result = $mysqli->query("SELECT * FROM schedules WHERE NOW() >= schedule");
But with no luck. I am getting the results with
while ($row = $result->fetch_assoc()) {
$id = $row['ID'];
echo $id;
}
Use now() to select rows where schedule is in the past
SELECT * FROM schedules WHERE now() > schedule
They are different because,
php time is based on the php timezone setting (inside php.ini).
database time is based on your system time (unless you set it).
The only thing that I have left for my assignment is to show the amount of new transactions since the user last visited his statistics dashboard, I thought I understood the concept of this fairly well, but it seems like I'm running into a problem.
This problem is that the current-date that the user has, and the current-timestamp that the SQL uses are not one and the same. (I would assume this varies based on time-zones?)
I guess what I'm looking for is what time=zone MySQL stores the DATETIME (Current Timestamp) field in, so I can get the current time-stamp of the user, his time-zone, and attempt to perform logic to make them the same.
Or is there an easier way around this? I'm currently using the DATETIME format in my dashboard to display information on purchase dates, which is formatted like so 2015-01-12 01:02:18 inside of a table.
Perhaps my query is just wrong, who knows:
function getNewTransactions($connection, $user) {
$statement = $connection->prepare("SELECT `lastcheck` FROM `login` WHERE 1");
$statement->execute();
while($row = $statement->fetch()) {
$d = $row['lastcheck'];
}
$statement = $connection->prepare("SELECT * FROM `transactions` WHERE `date` > :d");
$statement->bindParam(":d", $d);
$statement->execute();
$transactions = 0;
while($row = $statement->fetch()) {
$transactions++;
}
$date = date("Y-m-d H:i:s");
$statement = $connection->prepare("UPDATE `login` SET `lastcheck` = '{$date}' WHERE `username`=:name");
$statement->bindParam(":name", $user);
$statement->execute();
return $transactions;
}
If I swap the > around to < it does show older transactions, but they're off by a few hours.
http://php.net/manual/en/function.date-default-timezone-set.php
This should help you out with setting the timezone.
You can get the timezone from MySql with
SELECT ##system_time_zone;
or get the +/- offset from GMT with
SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);
In your situation you can try something like this
SELECT convert_tz(`lastcheck`, 'TIMEZONE_LASTCHECK_IS_STORED_IN', ##system_time_zone, ) as lastcheck
FROM `login`
WHERE 1
But ideally, all the datetimes in the database should be stored in the same timezone. That would eliminate your current problem. You could achieve this with ...
SELECT ##system_time_zone
... and save the value into the PHP variable $db_timezone_code
... then replace the $date assignment with ...
$db_timezone = new DateTimeZone($db_timezone_code);
$now = new DateTime('now');
$now->setTimeZone($db_timezone);
$date = $now->format('Y-m-d H:i:s');
... $date is now converted from the PHP servers timezone
... to the databases default timezone.
$newtime = date("Y-m-d H:i:s", time() + 600);
mysql_query("UPDATE rounds SET clock = $newtime WHERE `round`='$CurrentRound' ") or die(mysql_error()); //update DB
This code is failing to add the current time (+10 mins) to the MySQL database.
The cell in the database is datetime format.
I had done this before, but upon rewriting the code, it has stopped working.
You could use
UPDATE rounds SET clock = NOW() + INTERVAL 10 MIN WHERE round = '$CurrentRound'
To set the clock to 10 mins, per the time on the MySQL server.
Alternatively, you need to add ' around the $newTime variable
UPDATE rounds SET clock = '$newtime' WHERE round = '$CurrentRound'
change your query to this:
("UPDATE rounds SET `clock` = '$newtime' WHERE `round` = '$CurrentRound'")
I would very much appreciate your help.
I have a mysql db that contains a Datetime field. In that field I have a particular date and time,
for example:
2013-10-03 22:28
I then have a PHP script that gets a particular date and time from the $_GET command, values separately: year, month, day, hour, minute.
From this GET I created a Date as follows:
$datum = $year."-".$month."-".$day." ".$hour.":".$minute.":".$seconds;
$date = date('Y-m-d H:i',strtotime($datum));
What I need to do now is somehow compare this new date I created with the last date value in the database (the most recent). The point is that after I compare this I want to check whether the last value in the db is older than 5 minutes and only then do a particular action (insert new row), and if the last date in the db is newer than 5 minutes, do nothing.
Use "select max(datetime_field) from tblname" to get the most recent value for the Datetime field.
$now = new DateTime();
$dateFromDB = new DateTime($someValueFromYourDataBase);
// subtract 5 minutes from now and compare with the stored timestamp
if ($now->sub(new DateInterval('PT5i') > $dateFromDB) {
// database timestamp is older - do something
}
you can use SQL like this:
select count(*) from `table` where `datefield` >= '$date'
$date can be calculated like
$date = date('Y-m-d H:i', strtotime($datum) - 5*60);
5*60 - it is 5 minutes
for performance reason I suggest you to add index to datefield and change select like:
select `datefield` from `table` where `datefield` >= '$date' limit 1
I'm working with a table and there is field in my table which stores raw time() function value as date.
I want to get rows with today date from this table .
So i figure out when time() func returns a 10 digit number like 1316352184 the first 5 digits are for year , month , day which i need for getting today's date and the rest is for hour minute Second which i dont need
So i get today without hour and... like
$t = time();
$t = $t /100000;
$today =(int)$t;
Now i need to get rows with today date from the table but i'm not sure how to do that.
How can i get first 5 digits of stored date in database in my query to compare it with $date?
Something like this:
$sql = "SELECT * FROM TABLE WHERE ((int)date/100000) as date = $today ;
select * from table
where from_unixtime(unix_timestamp_field,'%Y-%m-%d') = curdate()
Why you don't use:
$sql = "SELECT * FROM TABLE WHERE date(date) = date(NOW());
What you have is a UNIX timestamp. The number of seconds since January 1st, 1970.
You can use date() and mktime() to work out what todays timestamp is, then do date > the timestamp. If that make sense.
Sounds like you should use the DATETIME or TIMESTAMP data type for your column so you can use MySQL's date functions.