Auto-Deleting MySQL Rows Based on Time Using Cron Job
The scenario presented poses a challenge: deleting rows from a MySQL database where the "Date" field falls below the current date, with the requirement that the script runs automatically at midnight daily, without any user input. This article will present a solution utilizing a PHP script and a cron job.
PHP Script for Data Deletion
Create a PHP script named "cronjobcommand.php" with the following code:
<code class="php"><?php include 'your_db_connection'; mysql_query("DELETE FROM your_table_name WHERE Date < NOW()"); ?></code>
This script establishes a connection to the MySQL database using the include statement. It then executes a query that deletes all rows from the specified table where the "Date" field is less than the current date and time (obtained using NOW()).
Setting Up Cron Job
Once the PHP script is complete, you need to set up a cron job to execute it daily at midnight. The cron job command for this would be:
0 0 * * * /usr/local/bin/php /path/to/cronjobcommand.php
In this command, "0 0" represents 12:00 AM (midnight), "*" denotes every day of the month, week, and year, and "/usr/local/bin/php" is the path to the PHP executable on your system. Adjust "/path/to/cronjobcommand.php" to the actual path of your PHP script.
After saving the cron job command in the crontab file, the script will automatically run every day at midnight, deleting rows from the MySQL table based on the specified date criteria without any manual intervention.
The above is the detailed content of How to Automatically Delete MySQL Rows Based on Time Using a Cron Job and PHP?. For more information, please follow other related articles on the PHP Chinese website!