MS SQL Entries that expire after 24 hours - php

Based on the solution here I tried using:
CREATE EVENT delete_expired_101
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 24 HOUR DO
DELETE FROM my_table WHERE id = 101;
on my php query, but it doesn't seem to work and gives me invalid syntax. Can you recommend me a way for this?
Take note I am using MS SQL not MySQL.

You need to use SQL Agent. The logic could be a SQL Agent job that is fired every 24 hours that deletes any data that has a datetime less than DATEADD(d,-1,getdate()). Please do some research on how to implement SQL Agent. If you need help with the code to delete data in a table based on a datetime value, please open a new question that includes that table's schema.

Ill be choosing #Chris H's suggestion by using delete function and set a table column which records timestamps.
Thanks for all the help

Related

mySQL script to get results in given date and insert into table

I'm really struggling for days with (what i think) is a pretty advanced operation that i plan to schedule to run in my database every week.
this is the structure of my table (unit_uptime_daily):
What i need to do is run a script every week that, for every unit_id that exists in that table, gets all the rows of that unit_id thats timestamp is that present day < 6 days (so all the unit_ids with a timestamp of the previous week) add up the total_uptime column of the 7 rows and insert the new row into a weekly table.
Effectively, i am grabbing the 7 latest rows for each unit_id, adding up the total_uptime and then inserting unit_id, result of added total_uptime and timestamp into a new table.
Thanks in advance, if this is even possible to do!
Use cron jobs. Most of hosting providers provides this facility. Google cron jobs to find more about it and here's an answer that could help you.
Run a PHP file in a cron job using CPanel
I have solved this by using PHP, I got the list of unique ids, and did all the maths in a loop, inserting each result into the new table. I had already done this but would have liked it to be possible in SQL.

Add data to a database, automatically remove after a certain time?

So, I've done quite a bit of googling on this topic, and I just can't find an answer. So, basically, I'm looking to make a small website, that will pull information from a HTML form, send it to a database, then after two hours, it will automatically delete itself. I have a basic theory on how this could work, but I can't figure out how to do it: I could pull the current time and date, add two hours to that, then put the time into an "expires" column in the database. Once the time is the one that is in the expires column, the data will be removed from the database. Sorry if this is a very "noobish" question, I'm still a bit new to databases with PHP.
Anyway, any help would be much appreciated! Thanks!
You could add a new timestamp column to your table which will automatically add the timestamp of when the row was created like so
CREATE TABLE t1 (
#your existing columns defined as before + this new column
ts_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Now every time you create a row on this table, MySQL does all the work of recording when it was created.
Assuming you may not be able to create a cron job on your host you could then add the deletion code in the most obvious place in your existing site code to do the removal.
// remove old stale data
$sql = "DELETE FROM user
WHERE ts_created < DATE_ADD(NOW(),INTERVAL -2 HOUR)";
if ( ! $mysqli->query($sql) ) {
// log $mysqli->error somewhere
}
ALthough a cron job seems a good idea at first sight, in order to make sure things are always accurate on this table you would have to run it every 30 seconds or maybe even more often. That would get in the way of other activities on this table, if the site was busy that could be a problem, if it was not busy you would just be running the cron unnecessarily most of the time.
If you add the deletion code just before you present this information to the user at least it would only be run when required and you would also ensure that the table was always accurate at the time the data was presented to the user.
You can ensure the scheduler starts when MySQL is launched with the command-line option --event-scheduler=ON or setting event_scheduler=ON in your MySQL configuration file (my.cnf or my.ini on Windows).
Run this query statement in mysql
SET GLOBAL event_scheduler = ON;
Create an mysql event scheduler using following - this will behave like Cron Job but actually it is a mysql trigger on specific interval. This is triggered from mysql server.
CREATE EVENT e_hourly
ON SCHEDULE
EVERY 1 HOUR
COMMENT 'Clears out sessions table each hour.'
DO
DELETE FROM table_name WHERE UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(remove_time) > 120
http://dev.mysql.com/doc/refman/5.1/en/create-event.html
http://www.sitepoint.com/how-to-create-mysql-events/
Pardon my explaination - I myself have implemented this just now and it worked.
Just add a column remove_time (DATETIME) and set the time you want the row to be deleted. Than use cron (configuration depends on webhosting you have) to run this query (probably as poart of PHP script):
DELETE FROM table WHERE remove_time <= NOW()
You can configure cron to run every minute (or less/more, depending on your needs).
Try implementing a cron which will run at specified time automatically to check and delete the rows whose created_at is less than the current_time by 2 hours.
On how to implement cron, check Skilldrick's answer here
Thank you
:)

Drupal created timestamp in SQL?

So when user are created in drupal website it creates a table row in SQL database, everybody knows that, but there is column created witch stands for create date. It contains int type, something like this 1341319209. I checked, it isn't the milliseconds from 01.01.1970.
The question is how can I convert it to normal date format using php or SQL Query? I tried to find how drupal does that, bet no success. Can someone please help. Write some code or give me a clue. :) Thanks.
You may try this:
MAKETIME( seconds / (60*60),
seconds / 60,
seconds % 60 )
or you may also try to use FROM_UNIXTIME()
SELECT
from_unixtime(timestamp)
FROM
your_table

Remove Mysql row after specified time

I'm trying to create a computer reservation system, where user chooses a computer and select the time how long he will be using this PC. In that time other persons can't reserve this pc, I need to find a solution, how to automaticaly delete all rows containing reserved pc's after their time expires. Thank you for the advice.
The common way to handle this is to store an expires_at timestamp on the reservation row. Then your query to find any "open" reservations would have WHERE 'expires_at' < NOW() or something similar.
This is an untested answer, that may only be a suggestion, but I just started looking at these, so am interested in feedback as well. i'm still working through possibilities and drawbacks, but it might well suit your need.
Take a look at MySQL Events, an article about it is here, and official syntax at Mysql Docs.
Per the article:
An event is similar to a trigger. However, rather than running in
response to a data change, events can be scheduled to run any number
of times during a specific period. In effect, it’s a database-only
cron job.
Pondering this, I'd envision a procedure that deleted anything >1hr (if that's the expiration). This procedure would be TRIGGERED on new inserts to get rid of anything expired at that moment, but also in an event to run every 15 minutes or so so that automatic deletes by the trigger aren't dependant on somebody else adding a reservation to trigger that procedure.
If your server is linux, you can use cron jobs to check once a day every reservation dates. If these dates have expired .. modified field reserves to be available.
Normally I would do it this way:
when storing a reservation, store date_from and date_to both of datatype DATETIME
when checking if there is a computer free check for all computers and filter with WHERE '{$my_date}' >= date_to AND '{$my_date}' <= date_from - by this You should be able to get all the PCs that are not reserved within a certain time...
To be complete in the solution, you need to run a CRON job which calls a query to remove all reservations that have a reservation_time + (15 * 60) < unix_timestamp().
I am assuming you have a time that the reservation was placed or started and are using UNIX/Epoch Timestamps.
Instead of doing a expires_now, if you know it will always be a fixed interval ie 15 minutes, you can do:
DELETE FROM reservations WHERE reservation_time + (15 * 60) < unix_timestamp()
Something you could look into is managing cron job's from PHP, http://www.highonphp.com/cron-job-manager.
The above script will, when a reservation is created, insert an entry into /etc/cron.d/ and you could configure it to run at the expected reservation endtime. Then inside the php file which would be executed, you could do:
DELETE FROM reservations WHERE id = :id

Recording time/date PHP form is inserted into SQL database?

I'm looking to order certain uploads by time order arrived (descending), but I'm not sure how I would record the time and date of submission using PHP/SQL. I'm pretty new to this, learning by coming up with projects and working through them as best as I can. Thanks for whatever help you can give me.
EDIT: I understand that the those functions exist, I just have no idea how I would implement them.
MySQL supports TIMESTAMP fields that can be automatically updated when the record is updated.
When you specify DEFAULT CURRENT_TIMESTAMP, the current time is inserted in new records. When you specify ON UPDATE CURRENT_TIMESTAMP as well, the timestamp is updated when the record is updated. That way, MySQL can automatically log the time for you.
You can do this using MySQL's NOW function.
Also see MySQL's Date and Time functions : http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
You have to create a column for saving the date and time.
I often use the following two columns:
created DATETIME DEFAULT NOW(),
modified DATETIME DEFAULT NOW()
That's all. If you insert a new record, MySQL will automatically update created and modified to the current date and time.
And if you want to order all uploads by their creation date:
SELECT * FROM uploads ORDER BY created DESC
Also see: http://sql-info.de/mysql/examples/CREATE-TABLE-examples.html#1_5

Categories