Auto-delete messages in MySQL database - php

Hi I have a MySQL database table where a user inputs messages (via a form) and I was wondering if there is a way to automatically delete a message after say 1 minute has passed?
The code i'm using is PHP.
Thanks very, very much for any replies :)

Well, you could always run a delete query before you do anything else. For example whenever you check for messages, first delete all messages older than 1 minute.
I think I would rather just not get the messages older than 1 minute though. It can be nice with a log :)

I can think of two ways to achieve that.
Make a script to run every X minutes and make any changes in your db.
Delete all expired records before or after inserting new records in your script.

When a message is inserted to the DB, store a time_created timestamp. Then in your PHP, you only display messages whose timestamp falls within 1 minute of the current time.

Use a cron job to purge old messages.

You could make a cron script to run every minute and delete all old messages
or make a valid_until column in your table, and set it to NOW()+60 - then only show rows which have valid_until >= NOW().

Building a cron service is the first thing that pops into my mind, although is probably an unnecessary complication.
You can call the delete in the same script that does the insert after a sleep of 1 minute.
sleep ($seconds);
// call the delete query
Another way is to pass the delay logic to a Mysql trigger that will do the delete for you.
SELECT SLEEP(<seconds>);

Solution 1: user cron job which runs every minute to check and delete
Solution 2: use ajax do that job
I personally suggest the first solution but if u have no SSH access to the server u have to choose the second one :D

thanks for all the replies/help :) the first suggestion by Svish 'You could always run a delete query before you do anything else. For example whenever you check for messages, first delete all messages older than 1 minute.' will work...so obvious don't know why i didn't think of that doh! Thanks again every1.

Related

Update database table cyclically every 5 minutes

I have to populate and update one of my MySql database table using a complex and expensive query, based on selection from other table's data. This table doesn't need to be always fully updated when i make a query on it, but i'd like to have a cyclic update every 5 minutes.
This automatic update should be infinite and i need to be sure that it never stops.
After some research, i've found some solution, but i don't know which is better for security and performance.
One of these could be my goal:
Don't create table and make complex query from php every time to get the desired result
Create a php script that repeats cyclically and update table db, maybe using Cron Job.
Update table using a sql event
I think that first solution could be to expensive since query is complex and there could be many request every second, but the result is always updated. I don't have experience about Cron Job, so i can't know if it could be a good idea or not. For the third solution, i still don't have database privileges to run events, but i'd like to know if it could be a valid solution.
All other solutions are welcome, thanks.
Do not use cron. Think about what will happen if one instance goes beyond 5 minutes and the next starts up. Eventually you will have hundreds of copies bogged down stumbling over each other.
Instead have a single job in a loop doing the update. (OK, you could have a cron job to perform a "keep-alive" task of restarting the query if it dies.)
The job would
CREATE TABLE new ...
INSERT INTO new SELECT complex-stuff...
RENAME TABLE real TO old, new TO real;
DROP TABLE old;
loop.
I would opt for Cron Job.
It doesn't clog any request, since it's executed from the operating system.
You can define which user executes the script (cron -u apache -e).
Easy to define interval. (i.e. every 5 minutes */5 * * * * php /path/to/script.php).
It's loggable.
Additional Notes
I had a cron job running under root and it worked just fine. My problem was that the project had a private logging mechanism that each log file would be created by apache user. By running it from root, sometimes the file would be created by root and after that, the scripts being executed by apache would not be able to APPEND to the log.
I also had an emailing script that would run once every 2 minutes that got stuck for 1h. Turns out, because of a bug in the application, an invalid email address (somethingwithoutatsign.com) was inserted into the database, which made the PHPMailer library throws errors. After that, I added a catch block that would send an email to me whenever an exception was thrown. Now, if the script stops running because of bad execution, I get to know right away.

Does a Cron Job a good idea to perform this task? PHP

I'm implementing an application that would check if the time is 4 or 6 or 12 hours after the data was inserted in the database.
So for example:
The data was inserted 1pm, then it's already 5pm (so this is 4 hours after the data was inserted), my application would process another task (no need for an explanation for this, I got it cover :D )
So this is a picture of my database fields:
id | name | time_added | time_to_check
ID is of course a type INT()
name is Varchar()
time_added is a type INT() because I am using time() function of PHP to insert a value.
time_to_check is a type INT because this is the field where i'll insert the 4,6, or 12
So my question is how would I implement this one? Is setting up a Cron Job a good idea to perform this task?
If Yes, every what time should I run the Cron Job (every 15mins,1Hour, Once a day)? I know there are lots of consideration in doing this task. So I need your ideas guys.
If you have an idea please share it to me or even code how you think to implement this one, it would be a great help!
Thank you very much! :)
ADDITIONAL INFO:
My concern about running it every minute is that not all of the data are inserted at the same time. Like for example: Data1 was added 3:15pm and time to check is 4 hours
Data2 was added 3:20pm and time to check is 4hours. What if the cron job didn't execute during 3:15pm or 3:20pm, what should I do?
If you need data to be routinely processed at 4, 6 or 12 hours after insert, you could also look at the Linux (not PHP!) 'at' command which allows you to queue processes to execute at a particular time. If you are expecting a lot of inserts then cron remains a better option though.
Cron is probably your best bet, having it check the database for records to check and going through them.
As for how often you want it, it mostly depends on how accurate you need the time to be. For instance, in my game I have a cron running every minute to check for fleets arriving at their destinations, but only every hour for checking if any banned users have served their sentence and need unbanning.
Yes a cron job would be good for this task. You would need to run it in an LCM of the times you'd like to check it. So from what I can see you should run it after 2 hours. (There would be a slight margin of error though - due to rounding). If you need complete accuracy you should check it every minute
I would recommend todo this task with a cronjob. The usage and some examples are explained here: http://en.wikipedia.org/wiki/Cron
The timeframe depends on your needs. If you check for 4,6 or 12 hours a cronjob per hour seems to be ok.

How do i auto delete a row of data in my database after 15days?

i want the site(if possible the database itself) to delete a row data in the database, without interacting with the site like opening or loading it.
i searched some tutorials/post but i only saw codes that need to be interacted.
Thanks.
Sorry for the bad English.
Run a cronjob or other scheduled process on your server
If you don't have access to cronjob you could run a small script at the bottom of a website. With the script, you check when the script was last run and if it's 15 days ago, check the dates of the rows in the database.
But, cronjob is easier, better and preferred.
You need to record the date that the entry was made in the db. Then write a script that would run as a cron job to check the dates of rows in the table and delete if it is up to 15 days

Need to reset database table every week

So I have a game which has a scoreboard based on weekly scores. At the end of the week I would like it to automatically delete all the entries and cache new values again. Issue is I don't know how to trigger such an even via PHP! Any help?
Sounds like you should set up a cron job.
It seems you have unusual database design.
I know no site (gaming or not) that erases weekly data.
The purpose of database is to hold data. Why not to let it just do it's job?
Create a small php file which connects to mysql and TRUNCATES the table ( better and faster to truncate instead of delete all ).
And add this to your crontab.
0 0 * * 0 PATH_TO_PHP myFile.php
Here is a crontab tutorial :
http://clickmojo.com/code/cron-tutorial.html
Generally these type of activities are carried out using Cron Jobs or Task Schedulers which will run periodically to perform the action you would specify.
I think the easiest way would be creating a PHP script which deletes everything on the table, then creating a crontab job for it.

Changing the status of a field in PHP after a period of time

For example I made a reservation for a restaurant and it expires in 24 hours. In the reservation table of the db (MySQL), how do I automatically update the status to expired after 24 hours? What approach would you guys suggest? Thanks in advance!
Don't really know the problem you're trying to handle but I'd store the timestamp when the reservation was made and have a field which stores after what interval from the point reservation was made does it expire (24 hrs in your case) and that's it. The rest should be handled at the point where you read/display that information.
Besides if you still really want to CHANGE the value in DB go for a cron that regularly updates the DB
Running periodical tasks is usually done with cron.
Here are some instructions how to use it on drupal (which is php/mysql)
Use cron like Unreason said or MySQL events, see Create event.
using cron can be liitle difficult
just run update query by comparing timestamp value with your time limit.
it will work.
I would suggest the following two methods.
To run a cookie at the background and check it out if the time (here in this case 24hrs) ran out or not..
Store the entry in the database with DATETIME type. As we check whether the user logged in or not with session variables. In the similar way for every click in the site, call a function to check whether the time is lapsed or not.

Categories