Home > Database > Mysql Tutorial > body text

How to Automatically Delete MySQL Rows Based on Time Using a Cron Job and PHP?

Susan Sarandon
Release: 2024-10-28 04:33:30
Original
510 people have browsed it

How to Automatically Delete MySQL Rows Based on Time Using a Cron Job and PHP?

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>
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!