SQL Delete All Column Values Older Than 20min - php

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";

Related

Show all results from database where mm/dd/yy date is "today" or greater

I am using HTML input type="date" to allow users to input appointment dates.
Now I want to query the database and show all appointments that are "today" and in the future.
Not dates that have already passed.
Here is my SQL Script
$today = date('d-m-Y');
$sql = "SELECT *
FROM `client1`
WHERE `client` = '$customer'
AND DATEDIFF('$today', `date`) >= 0
ORDER BY `id` DESC";
Can someone guide me as to how I can achieve this?
I have seen several directions online but I want to have the sorting done at the moment of query.
I have solved the issue!
My date() format was incorrect because HTML input type="date" inserts YYYY-MM-DD into the database =/
$today = date('d-m-Y');
should be
$today = date('Y-m-d');
My operator >= should have been <= to show today and future dates.
Thanks everyone for the help. I should have tried fixing it for 5 more minutes before posting.
Why are you using PHP to compare dates in the database? I assume its a date field so you can use MySQL to do it for you:
SELECT *
FROM `client1`
WHERE `client` = '$customer'
AND DATEDIFF(date_format(now(), '%Y/%m/%d'), `date`) >= 0
ORDER BY `id` DESC
None of the responses have specified sargable predicates. If you perform an operation on a column in the where clause, there is no discernible stopping point.
where ... some_function( some_field ) = some_constant_value ...
Even if some_field is indexed, a complete table scan must be performed because there is no way to know if the output of the operation is also ordered.
From my understanding the date column is in a sortable form -- either a date field or a string in lexically sortable format 'yyyy-mm-dd'. That being the case, don't do any operation on it.
where ... some_field >= now() ...
Thus the system can use the result of now() as a target value to find exactly where in the index to start looking. It knows it can ignore all the rows with indexed values "down" from the target value. It has to look only at rows with indexed values at or "up" from the target value. That is, it performs an index seek to the correct starting point and proceeds from there. This could mean totally bypassing many, many rows.
Or, to put it bluntly, ditch the datediff and do a direct comparison.

Altering a MySQL query to work in SQL Server

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.

UPDATE row relative to CURRENT_TIMESTAMP is not giving the correct value

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;

mySQL Select records within past hour

I'm setting up basic cookie tracking and validating that by making sure the cookie is on their computer AND their IP matches the record I stored AND the record was stored within the past hour. I'm getting hung up on selecting the mySQL data from within the past hour.
As it stands, the column in my table is called 'timestamp', and it just contains the full timestamp inserted with NOW(). I checked around and thought I found the right call, but this didn't work:
$q = "SELECT * FROM conversion_data WHERE ip='$ip' AND timestamp < DATEADD(HOUR, -1, CURRENT_TIMESTAMP) ";
Taking out the timestamp call, it all works fine, so it's just that one part.
Thanks!
Try:
$q = "SELECT * FROM conversion_data WHERE ip='$ip' AND timestamp > DATE_SUB(CURDATE(), INTERVAL 1 HOUR)";
Your current query will select rows that are older than one hour. Changing the timestamp predicate so that it will fetch rows that have a time that is newer than or equal to, i.e. greater than or equal to, should work.
$q = "SELECT * FROM conversion_data WHERE ip='$ip' AND timestamp >= DATEADD(HOUR, -1, CURRENT_TIMESTAMP) ";
Please note that I'm not sure if dateadd works like this for mysql, apply a relevant function in your case.

Database living in the past?

I have events in my MySQL database wich all have a date. When I perform a SQL query to get all the events in the future, I get an error... Although, the date of the events are in the future. When I change my SQL request to select dates in the past, I get those from the future...
The SQL statement below has worked before, but for some reason it stopped working...
I use this SQL request:
$sql = "SELECT * FROM calendar WHERE date >= CURDATE() order by `date`";
I get an empty array as result...
However if I change the query to this, I get all the events in my database:
$sql = "SELECT * FROM calendar WHERE date <= CURDATE() order by `date`";
This is my database data. In my opinion, all data are in the future...
The format of the date table is a default date-type:
When I ask my server about the time echo date("Y-m-d"); I get todays date as result...
So where do I make a mistake?
You may be checking the wrong date field. Do you have a created date as well as a scheduled date?
I could be crazy from the cold medicine I am on at the moment, but your date table can't possibly be the date of your calendar items, the id filed is only an int(2), that seems kind of small.
maybe something simplier? I notice the column name in your table is date, which also is the name of a function date() that returns the date part of a datetime value. If thats the case
$sql = "SELECT * FROM calendar c WHERE c.`date` <= CURDATE() order by `date`";
would do the trick. Even if not mysql itself, the gui app youre using (seems like phpmyadmin to me) might get confused.
(btw, you forgot the closing tick of date in the order by clause)
getting an empty set is meaning nothing is found matching. I would look at your formatting of your date. The only other thing i was thinking is that it is comparing an unmatched type so just returns an empty set.
use DATEDIFF :
DATEDIFF
WHERE DATEDIFF(date, CURDATE) > 0
Before you make your query, run this one:
SET time_zone = '-2:00'; // or whatever your time zone is.
Don't ask me how or why, but I've truncated my table and re-inserted some data and my query seems to work just fine:
$sql = "SELECT * FROM `calendar` WHERE `date` >= CURDATE() order by `date`";
So, despite the fact the problems seems to be solved by truncating my table, I would like to know the answer to the why-question... Anyone can provide me with it?

Categories