Home > Database > Mysql Tutorial > How to Automate MySQL Query Execution as a Cron Job Without Manual Password Entry?

How to Automate MySQL Query Execution as a Cron Job Without Manual Password Entry?

Susan Sarandon
Release: 2024-11-17 07:38:03
Original
264 people have browsed it

How to Automate MySQL Query Execution as a Cron Job Without Manual Password Entry?

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");
Copy after login

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

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

Option 2: Running a PHP File

To run a PHP file as a cron job, first save the query as a PHP file:

Copy after login

Then, modify the crontab file:

crontab -e
Copy after login

Add the following line:

* * * * * /usr/bin/php /path/to/php_file.php
Copy after login

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!

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