PHP / MYSQL Inserting current time to datetime - php

$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'")

Related

Mysql update database where date == -15 from current

i've been looking around for a way to do this; I found one tutorial that suggested using the dateadd (which i found out is date_add in mysql) function... but I've had no luck with that.
I need to have something that updates the database every 15 minutes or so via a Cronjob... The cron job is already set up (Php file), but i cannot get the DB to update every fifteen minutes.
anyway, this is the code i've got currently--i was really stressing out trying to figure out how to get it to work... so i know what i'm doing doesn't actually work.
UPDATE starinformation SET starOwner = nextOwner, death = 'off', wifi = 'on' WHERE underSiege = 1 AND siegeStart = (current_timestamp)-15
I've also tried doing this
$date=date('-15 minutes'); $sql = "UPDATE starinformation SET starOwner = nextOwner, death = 'off', wifi = 'on' WHERE underSiege = 1 AND siegeStart = ".$date
You can try this.-
<?php
date('Y-m-d H:i:s', strtotime('-15 minutes'));
?>
Please take a look here, how to deal with times using MySQL
Add 2 hours to current time in MySQL?
Do you mean something like
DATE_ADD(NOW(), INTERVAL -15 MINUTE)
The current time minus 15 minutes can be represented by the two functions CURTIME and SUBTIME:
SUBTIME(CURTIME(),'00:15:00.0');
So, based on your posted statement, the modified version is:
UPDATE starinformation SET starOwner = nextOwner, death = 'off', wifi = 'on' WHERE underSiege = 1 AND siegeStart =SUBTIME(CURTIME(),'00:15:00.0')
This might be what you have been looking for:
UPDATE starinformation SET starOwner = nextOwner, death = 'off', wifi = 'on' WHERE underSiege = 1 AND siegeStart = DATE_SUB(NOW(), INTERVAL 15 MINUTE)
Here DATE_SUB subtracts the given date NOW() with given INTERVAL.
If siegeStart of datetime or timestamp data type then
Use
siegeStart = ( current_timestamp - interval 15 minute )
in the update statement.
But the update will only work if the seconds part of the siegeStart also matches.
If you can omit seconds part of your date, then
Use
date_format( siegeStart, '%Y-%m-%d %H:%i' ) =
date_format( current_timestamp - interval 15 minute, '%Y-%m-%d %H:%i' )
Refer To:
INTERVAL clause: INTERVAL expr unit
DATE_FORMAT(date,format)

MySQL date comparison from PHP

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

Comparing timestamp to current time from database

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.

MySQL current_timestamp - timestamp throws wrong results

Hello in a PHP Script i have the following MySQL Query
$query_players = "SELECT (current_timestamp -`Online_since`) AS `Since` FROM `streams` WHERE `Team` = $temp AND `Online` = 1 ORDER BY `Viewers` DESC";
then i have:
$since = round($obj_players->Since /3600);
As you probably can imagine $since should contain how long the player is already online in hours. Strangely it has wrong results. Its like the time goes faster in MySQL :P
For example after about 15 minutes it already shows "Online since 1 hour" another approximately 30 mins later it already shows 2 hours and so on.
Anyone know what could be wrong? Maybe current_timestamps is the problem?
current_timestamp is not really measured in seconds. So dividing the difference by 3600 doesn't yield hours, but some arbitrary value.
The difference after 18 minutes is 1800 and round(1800/3600) = round(0.5) gives of course 1.
Depending on your real column type use either timediff() or timestampdiff() for your calculation.
Try using TIMESTAMPDIFF:
$query_players = "SELECT TIMESTAMPDIFF(HOUR, NOW(), `Online_since`) AS `Since`
FROM `streams`
WHERE `Team` = $temp
AND `Online` = 1
ORDER BY `Viewers` DESC";

Need Help Setting Future Date in MySQL via PHP

I am trying to insert a future date into a MySQL table from PHP. I have been able to insert the current date using strtotime but when I add time to this call it does not seem to insert it. Here is the code:
<?php
$currentDate = strtotime('now');
$expirationDate = strtotime('+ 90 days');
include_once "mysql-connect.php";
$cur = "UPDATE table SET current_date = FROM_UNIXTIME($currentDate) WHERE ...";
if (!mysql_query($cur,$con))
{
die('Heres Your Error: ' . mysql_error());
}
echo "the date is set";
$exp = "UPDATE table SET expiration_date = FROM_UNIXTIME($expirationDate)
WHERE ...";
if (!mysql_query($exp,$con))
{
die('Heres Your Error: ' . mysql_error());
}
echo " expiration date is set";
mysql_close($con)
?>
Like I said, when I run this it will insert the current date into the current_date row as requested. For some reason it will not insert expiration_date which is 90 days in front of the current date. I have verified that the expiration date is being picked up as 90 days in the future. Why is this not working?
You can do it in MySQL directly:
$days = 90;
$sql = "UPDATE ... SET expiration_date = DATE_ADD(current_date, INTERVAL $days DAY);"
which'll save you the excess round-tripping from datetime->unix timestamp->datetime.
It is a bad idea to use strtotime() function because it does not always work nicely.
Rather than doing dates in PHP, I'd suggest you do them directly in MySQL that provides a decent pool of date-time functions - http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html.
For your query, you can do:
UPDATE `table`
SET `current_date` = NOW(), `expiration_date` = DATE_ADD(NOW(), INTERVAL 90 DAY)
WHERE ...;
By the way, for your query case, does the second UPDATE return any errors. Which part of the following IF executes?

Categories