I have a query that was originally written for MySQL that writes a timestamp to a record. The query adds 15 minutes to the timestamp, based on the time the query is run.
$query = $con->prepare("UPDATE TableName SET
LockExpiryTime=ADDTIME(NOW(),'00:15:00'),LockKey=:lockkey
WHERE NOW() > LockExpiryTime AND formID = :formid");
$data = array('lockkey'=>$_SESSION['LockKey'],'formid'=>$_SESSION['formId']);
$query->execute($data);
I know that NOW() is not used in SQL Server, so I'm wondering how I can reconfigure this query to work in it and write the timestamp to a timestamp field. Or would datetime be better in this case?
EDIT: I should explain what this is used for. When the user logs into a form, a lock key and expiration time are generated. The lock lasts fifteen minutes. When the user logs out, both the key and expiry time are reset.
You can use this DATEADD(MINUTE, 15, getdate()) in SQL Server,
instead of ADDTIME(NOW(), '00:15:00') which you used in MySQL.
Related
I have a PHP script which creates a new order and inserts the time NOW + 15 minutes into the database.
After 15 minutes have expired the user cannot access the order page.
On the admin panel I only want to show records that have not expired, so my question is what select statement would I use to do this, and which would be the most efficent?
SELECT * FROM `orders` WHERE datenow > date
The "date" is the date of the order + 15 minutes
P.S.
Aternativly, is there any way to do this using PHP so I don't have to put too much stress on the database?
Many Thanks!
Given that you want records that have not yet expired, you want all records where date is greater than NOW().
SELECT
*
FROM
`orders`
WHERE
`date` > NOW()
As the comments mentioned, it is usually better to handle this on the database side; rather than transfer (assuming you have split database and web servers) the entire data set to filter it in the application code.
The other benefit of having all the datetime functions be on the same server (in the database in this case), is that especially on some shared hosting environments, the timezone for the database cannot be changed. Therefore, you want the time comparisons to occur in the same timezone.
I tried but didn't get the success in this scenario.
actually data values are saving based on users timezone dates,
so i want dynamically passing some parameters to check and get the values from database. but problem is how can i pass parameter as user time to mysql query?
Per day if 10 records are there for User1, i want recent past one hour record based on user timezone date only.
$select = db_select('{emp}', 'e');
$select -> addField('e', 'name', 'name');
$select -> addField('e', 'date', 'date');
$select -> condition('e.name', $name);
$select->where('date >= DATE_SUB(NOW(), INTERVAL 1 HOUR)');
$select -> orderBy('e.date', 'DESC')->range(0,1);
$subresult = $select -> execute()-> fetchObject();
in that query now() taking as a system time, in that place how can i pass user's time?
any help?
See this. How to handle MySQL timezone in script
To store time data so it looks right to users in different time zones, you need to do several things.
First, ask each user to specify her timezone. These are specified as strings like 'America/New_York' and 'Asia/Dili'. Store that information as part of the each user's profile.
Next, each time you make a connection from your application to MySQL from your application, set the connection time zone with a command like this:
SET time_zone = users-time-zone-choice
Finally, always store time information in TIMESTAMP data types, rather than DATE or DATETIME datatypes. TIMESTAMP values are always converted from local time to UTC upon storage, and always converted back to local time upon retrieval.
So timestamp_column >= NOW() - INTERVAL 2 HOUR and similar queries work correctly.
datetime_column >= NOW() - INTERVAL 2 HOUR won't work.
Then, the NOW() function will display in the user's local time. So will the contents of TIMESTAMP data items. The contents of DATETIME and DATE objects will not display in users' local time; they are always stored and retrieved without respect to timezone.
It's best to set your server default timezone to UTC.
You can try this out; these commands should give you some interesting results.
set time_zone = 'Asia/Dili';
select ##time_zone, now(), utc_timestamp();
set time_zone = 'America/Phoenix';
select ##time_zone, now(), utc_timestamp();
set time_zone = 'Asia/Jerusalem';
select ##time_zone, now(), utc_timestamp();
Tonight I'm going to start working on a php script to set as a cron. The script is going to delete all the values of a particular column that are older than 20min. It's going to do this by checking the timestamp of when the value that will be deleted was entered. The timestamp will be stored as another column value on the table.
It seems like a pretty simple script to write, but my knowledge of SQL is lacking. I know I can compare the times in PHP, but I was just reading that it's possible to do it all in a SQL statement as well. If someone can please correct my delete statement it would be appreciated.
$query ="DELETE `key` FROM $table WHERE `time`<DATE_SUB(NOW(), INTERVAL 20 MINUTE);"
I need this statement to check the key value for the whole table, and I'm not exactly sure which PHP time function corresponds with the SQL comparison. Would I just use DateTime(); to set the timestamp?
$query = "DELETE `key` FROM $table WHERE `time` < ADDDATE(NOW(), INTERVAL -20 MINUTE)";
You can use the following query :
$query = "DELETE `key` FROM $table WHERE `time` < CURRENT YEAR TO MINUTE -20";
I have an API fetcher script that reads values from XML files and updates data to mysql. It updates the database everytime it's called via ajax.
Now I want to set an interval for about a day before the query gets updated. Which php function or method should I use?
I think I should make myself a little more clear, these are the steps:
xml file read with php
Echo the results.
--->If (mysql updated time > 24*60*60 seconds) update the db
--->if not, do nothing.
I can't figure out how should I process the step (3)
Well! as far as i understood your question. I think you should do with SQL not with PHP.
Save update time in db with query of Insert. And call a stored procedure every time you update. like in MySQL:
Begin
//Adding updtime column value into a Variable called #a
select #a:=updtime from abc order by id desc limit 1;
//DATE_ADD() is a function of MySQL to get Time after adding Hours or Minutes etc. More can be found in MySQL Manual online
if DATE_ADD(#a, INTERVAL 24 HOUR) > now()
then insert into abc values ('XML',now());
end if;
End
You can also do it without a variable and that would be much better as
if DATE_ADD((select updtime from abc order by id desc limit 1), INTERVAL 24 HOUR) > now()
The best solution that I can think of is a Cron Job.
This page will give you detailed information
I am trying to update a MySQL table with an 'expiration date'. I've collected a timestamp value for all my rows as people have registered into the table but now I want to create an expiration date relative to that timestamp (not to relative to the current time). Here's my code:
$timestamp = $row['timestamp'];
$sql_update = "
UPDATE jobs
SET expiration_date = DATE_ADD('$timestamp',INTERVAL 56 DAY)";
$result_update = $mysqli->query($sql_update) or die($mysqli->error);
Understand that this is being run in a 'while' loop so it's running through each row of the table an updating them as it goes. The issue is that I ran it once and all it did was update the 'expiration_date' row to 56 days from NOW not 56 days from the timestamp's value. The timestamp is set on CURRENT_TIMESTAMP for when the a new entry is registered which I'm assuming is the problem. I've echoed out $timestamp to troubleshoot and it echoes out the correct value (not the current time) when I echo it but when it goes to actually update the expiration date it seems to be drawing from the fact that it's a CURRENT_TIMESTAMP. Is there a way to explicit query for the value of the timestamp?
I'm hoping to find a way that doesn't involved restructuring the database. I know I could have it so instead of a timestamp row, I could make it a datetime row and set it to the value of NOW() when database is being initially queried to add a row but I'd prefer to find a solution within the way the table is currently set up. Thanks!
Probably somehow the value in $timestamp is wrong.
Try adding the timestamp directly in the query using the column name. E.g. : DATE_ADD(timestamp,INTERVAL 56 DAY)
What you are currently doing, hardly makes any sense. You first get the timestamp from the database and assign it to the $timestamp variable, only to use it in the query again..
In situations like these, you can better directly use the column name to access the data in your query.
I wonder why are you running this query in loop ?
You can use only one sql statement. Update from select;
update jobs a set a.expiration_date = DATE_ADD(a.timestampFieldName,INTERVAL 56 DAY), a.timestampFieldName = a.timestampFieldName;
I supose that there is some "bug" (don't know) in MySQL because if you don't add a.timestampFieldName = a.timestampFieldName then this field will be set to current timestamp;