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
:)
Related
So here is what I am trying to accomplish:
User selects how often they want their post to be moved to the top of the page, whether it be every 30 minutes or every hour or every 2 hours, etc. They will be able to select how many times that it will do this. So if they select it to update every hour for 5 hours, it will then update the date/time in the database to the current time and then updates that time every hour for the next 5 hours and cancels it after the 5 hours are up.
I was thinking of running a PHP script like this to update the table since the ads are displayed by date DESC:
<?php
//cronjob.php
$id = $_SESSION['ad_id'];
$date = date('Y-m-d H:i:s');
$query = "UPDATE ads SET ad_date = :date WHERE ad_id = :id";
?>
Is there a best way to do that or will a CRON job that is selected by the user going to be too much load on the server to have users setting up CRON jobs continuously.
I saw this one approach and wonder if it is possible to set it up for this purpose. I am still getting familiar with CRON jobs.
How to start/stop a cronjob using PHP?
I will be setting this up on Godaddy's server:
Godaddy Cron jobs
Appreciate the help.
One method is to store the required updates in a new database table, containing fields such as the post id, how many times to update, interval, how many updates are left, the time at which the first update should take place ( or the time for next update ) .
Then, create a php script that fetches data from this table and take necessary action for each post. Check if it's time to update the post, if yes then update, else don't ( check time with accuracy upto minutes, don't check seconds. If you can, do this time checking with SQL and not in php to reduce the data being fetched ). It's better to perform all updates in a single query to maximise efficiency.
Then set up a cron job on the server that runs this php script every minute or whatever minimum time interval you need.
This way, you can get away with just one cron job😉
If you need even more efficiency, then at the end of this script, check if there are any more updates pending, if none then delete the cron job. Then, set up your code such that whenever a user creates a new update, check if the cron job exists, if it doesn't then create it ( this additional dynamic cron job is only for efficiency freaks. If there are frequent update requests, it might be better to avoid creating/deleting cron jobs )
I would like to store events' recurrences in a mySQL database (additionally, I'm working with Symfony 3 and Doctrine ORM).
For instance:
Every 3 days / Once a week / Bimonthly / Half-yearly / Once a year
What is the best way to store this kind of data in order to be able to easily perform queries on it?
Moreover, I want to create complex reminders based on these recurrences.
For instance:
From February to September: once a week and from October to January: bimonthly
How could I manage reminders' dates calculation? Should I store the start date and calculate the next dates each time, or should I store only the next date when a reminder is marked as completed?
(My use case: set reminders for watering plants).
Thank you a lot for sharing what do you think about!
Regards!
You can set events in MySQL itself or as pogeybait suggests, you can write a cron job and a command.
If you need the server to do something outside of the database, you likely need a cron job. If it's all contained within the database (such as just updating a "plants_need_watering = false" column to "plants_need_watering = true" without having to send an email or start some other program) then I'd say MySQL events are more suitable.
Here's a pretty good tutorial on events (although, I had to play around with the delimiters when I tried it): https://www.sitepoint.com/how-to-create-mysql-events/
Here's a simple event I wrote. You can see how it just updates a db column based on the date. I set the status of a my own "event" (not a MySQL event, but an entity from my application) to "Voting is closed." if the "voting_end" date is past today and this runs every 12 hours so I know I can't accidentally miss one. This is just entered once as regular SQL, you can practice and check results on a local dev machine by setting the schedule to every hour or so, check to see that it worked, then switch back to the actual desired timeframe to run the event: every week, every month, etc.
SET GLOBAL event_scheduler = ON;
CREATE EVENT switch_event_status
ON SCHEDULE EVERY 12 HOUR
DO
UPDATE event_status
INNER JOIN
event ON event_status.id = event.event_status_id
SET
event_status.value = \'Voting is closed.\'
where
event.voting_end <= cast(now() as date);
Also, here's the Symfony documentation on writing console commands. It's actually pretty easy. http://symfony.com/doc/current/console.html
And cron jobs to kick the console command off: https://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/
If you are on a Linux machine, you can use cron jobs to check however often as you'd like. Id create a console app to do this so the cron job is easier to call. It's easier than you think to create the console apps. For the database I'd store general info about each event (name, title, description) and an interval field which would say how often that even should trigger an notification. Initially store the current date and time when the event is added and then when the interval time passes trigger then notification and store the date and time of the notification. That's the simplest way I can think of. See more here http://symfony.com/doc/current/components/console.html for console commands.
I want to make a table where the entries expire 24 hours after they have been inserted in PHP and MySQL.
Ideally I want to run a "deleting process" every time a user interacts with my server, that deletes old entries. Since this is more frequent you should it will not have large amounts of data to delete so it should only take a few milliseconds.
I have given each entry a date/time added value.
How would I do this?
You could use MySQL's event scheduler either:
to automatically delete such records when they expire:
CREATE EVENT delete_expired_101
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 24 HOUR DO
DELETE FROM my_table WHERE id = 101;
to run an automatic purge of all expired records on a regular basis:
CREATE EVENT delete_all_expired
ON SCHEDULE EVERY HOUR DO
DELETE FROM my_table WHERE expiry < NOW();
you shouldn't do a delete process when a user interacts. it slows down things, you should use a cronjob (every minute / hour)
you'll want to index the added timestamp value and then run DELETE FROM table WHERE added < FROM_UNIXTIME(UNIX_TIMESTAMP()-24*60*60)
maybe you'll want to checkout Partitions, which divide the table into different tables, but it behaves as one table. The advantage is that you don't need to delete the entries and you'll have seperate tables for each day.
i think that YOU think that much data slows down tables. Maybe you should use EXPLAIN (MySQL Manual) and optimize your SELECT queries using indexes (MySQL Manual)
UPDATE Check out eggyal's answer - This is another approach worth taking a look.
You can look into using Cron Job, http://en.wikipedia.org/wiki/Cron Make it run once every 24 hours when it matches your requirement.
This will help
Delete MySQL row after time passes
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
I'd like to know the best way to implement in PHP a counter that, having been incremented by some events on the server during a day, would be reset to zero with a new day coming, i.e at midnight. Probably comparing the date associated with the last value of the counter with the current date would make it reset?
EDIT: What if the counter gets reset the moment when it's going to be incremented provided that the code somehow figures out that the last time the counter was incremented was yesterday or a day earlier? It would be good enough.
Are you storing your counter in a database? If so, you might just want to store the date of the last change along with it. Let me assume you have a table counters(name, value, date), then the following pseudo-code might give you an idea:
$counter_id='herpderp';
$today = date('dMY');
$date, $value = query("SELECT date, value FROM counters where name='$counter_id'");
if ($date!=$today) {
$value = 0;
query("UPDATE counters SET date='$today', value=1 WHERE name='$counter_id' AND date='$date'");
} else {
query("UPDATE counters value=value+1 WHERE name='$counter_id' AND date='$date'");
}
echo $value;
Depending on your server you're either going to either be able to implement a Scheduled Task (Windows) or CRON Job (Linux). This will be what allows your script to execute at a specific time of day (or night).
As for the counter, you can implement that in a few ways. For data integrity and security, I'd store the value in a database. To increment, fetch the value and increment it (there are also some ways, depending on your DBMS, to do this with a single SQL query). Otherwise you could always edit a configuration file with I/O commands in PHP.
Setting up the CRON Job / Scheduled Task
If you give me more information on your server configuration I can give you specific tutorials on where you can find out how to set up your task.
Once you've figured it out, you'll want to call a specific script. Your script in PHP can be set up as follows:
Compare the current D/M/Y to the previous days, most likely stored in your database or configuration file. If this checks out, update your database/file performing whatever analytic actions you deem fit.