Automating MySQL Row Deletion Based on Date
Facing a unique challenge, a developer seeks to automatically delete rows from a MySQL database where a specific column value ("Date") falls below a specified threshold. The task requires the script to run daily at midnight without any user interaction.
Solution:
One effective approach to accomplish this task is to utilize a PHP script in conjunction with a cron job. A cron job is an automated task that can be scheduled to run at specific intervals, such as daily at midnight.
PHP Script:
<code class="php">include 'your_db_connection'; mysql_query("DELETE FROM your_table_name WHERE Date < NOW()");</code>
This script establishes a connection to the database and executes a query that deletes all rows from the specified table ("your_table_name") where the "Date" column value is earlier than the current date and time.
Cron Job Setup:
To schedule the script to run automatically, create a cron job using your hosting or server control panel.
0 0 * * * /usr/bin/php /path/to/cronjobcommand.php
This command specifies that the cron job should run at midnight (0 0) every day ( *). The path to the PHP script should be replaced with the actual path on your server.
Additional Notes:
The above is the detailed content of How to Automate MySQL Row Deletion Based on Date?. For more information, please follow other related articles on the PHP Chinese website!