Automated MySQL Query as a Cron Job
Question:
Can a MySQL query be executed as a cron job without manual password entry?
Background:
The goal is to purge MySQL database entries older than a week daily using a cron job. The PHP query to execute is:
mysql_query("DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) , timestamp ) >=7");
Solution:
Option 1: MySQL Event Scheduler
It's recommended to use MySQL's event scheduler instead of cron jobs. To enable it:
SET GLOBAL event_scheduler = ON;
Create an event:
CREATE EVENT name_of_event ON SCHEDULE EVERY 1 DAY STARTS '2014-01-18 00:00:00' DO DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) , timestamp ) >=7;
Option 2: Running a PHP File
To run a PHP file as a cron job, first save the query as a PHP file:
Then, modify the crontab file:
crontab -e
Add the following line:
* * * * * /usr/bin/php /path/to/php_file.php
The above is the detailed content of How to Automate MySQL Query Execution as a Cron Job Without Manual Password Entry?. For more information, please follow other related articles on the PHP Chinese website!