Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete mysql row after time passes?

I have no idea where to start with this one:

I have a database that stores postID and Date.

What I want to do is have my website auto delete all rows where Date is less than today. This script can't have any user input at all. No button clicks, nothing. The script must run every day at midnight.

I've been looking all over the place for something that does this and I've found absolutely nothing.

like image 200
Sweepster Avatar asked Mar 26 '12 00:03

Sweepster


People also ask

How do I purge old data in MySQL?

To delete all rows older than 30 days, you need to use the DELETE with INTERVAL. Use < now() i.e. less than operator to get all the records before the current date.

How do I delete a row in MySQL?

To delete rows in a MySQL table, use the DELETE FROM statement: DELETE FROM products WHERE product_id=1; The WHERE clause is optional, but you'll usually want it, unless you really want to delete every row from the table.

How do I delete a row from a view in MySQL?

If you want a row to disappear from a view, you need to either delete the data from the real tables behind the view, or alter the view-creating SQL so that that particular row won't be shown in the view.

Is deletion possible in MySQL?

The Delete query in MySQL can delete more than one row from a table in a single query. This proves to be advantages when removing large numbers of rows from a database table. Once a Delete row in MySQL row has been deleted, it cannot be recovered.


2 Answers

You can use PHP script and use cron job on your cpanel.

Example:

cronjobcommand.php

<?php 
 include 'your_db_connection';
 mysql_query("DELETE FROM your_table_name WHERE Date < NOW()");
?>

I have attached a screenshot below for your more reference.

enter image description here

like image 109
hodl Avatar answered Oct 10 '22 00:10

hodl


For those out there who are on a shared hosting, like 1and1's, and can't use cron, here are 2 alternatives :

  • mysql events enable you to place a time trigger on mysql, which will execute when you'll want, without having to be fired by any kind of user input

  • if you cannot create mysql events because you're on 1and1 :(, an alternative is to use webcron

You just need to tell webcron the url of the php script you'd like to be run, and they'll trigger it for you at the intervals you want

like image 42
Vic Seedoubleyew Avatar answered Oct 10 '22 00:10

Vic Seedoubleyew