How to delete mysql row after time passes?

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


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


Why using cronjobs everyday?? Why not filter data on output. For example in your select check if post date equals today with adding a simple where:

SELECT * FROM `posts`
WHERE (DATE(`post_date`) = DATE(NOW()));

This way you're not required to do your database managements/cronjobs on any special time and it will be used just for database managements. Afterwards you can delete unnecessary data at any time using by mysql command like:

DELETE FROM `posts` WHERE (
    DATE(`post_date`) < DATE(NOW())
)

Most hosts provide a cron(8) service that can execute commands at specific times. You use the crontab(1) program to manage the crontab(5) file the describes when to run which commands.

There's a lot of functionality available to you, but if you write a program (shell script, php script, C program, whatever) that runs the appropriate MySQL commands, you can call the program via cron(8) in an entirely hands-off fashion.

Run crontab -e to edit your current crontab(5) file. If none exists, hopefully you'll get one with a helpful header. If not, copy this:

# m h  dom mon dow   command

The columns indicate the minute, hour, day of month, month, and day of week to execute commands. All the numbers in the columns are essentially ANDed together to decide when to run commands.

Thus, midnight every night would look like this:

0 0 * * * /path/to/executable

It's remarkably flexible, so put some time into the documentation, and you'll find many uses for it.