简体   繁体   中英

How to delete mysql data from table at midnight?

I have a mysql table and I want it to be "emptied" every night at midnight. I have searched for an answer on the web and came across nothing that seemed to help me. I had this idea of using javascript to get the current time and then run an if statement and see if it is equal to midnight and if it was to execute a php script that deleted the information.

Javascript:

var myVar=setInterval(function(){myTimer()},1000);

function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
    if(t == 12:00:00 AM){
            $.ajax({
                URL: 'delete.php';
            });
    };
};

delete.php:

<?php
require 'connect.php';
mysql_query("DELETE * FROM messages;");
?>

I have tested this by setting the time in the if statement to a time a few minutes ahead of my actual time and it does not work.

Implementing your own event scheduler, especially as a web page using JavaScript is a bad idea. Use for that either

  • a cron job to run DELETE statement through the mysql command line interface
    /path/to/mysql -u<user> -p"<password>" <db_name> -e "delete from messages"
     CREATE EVENT delete_messages_at_midnight 
     ON SCHEDULE EVERY 1 DAY STARTS CURDATE() + INTERVAL 1 DAY
     DO DELETE FROM messages;

If you go with MySQL event approach:

  • use SHOW PROCESSLIST to check if the event scheduler is enabled. If it's ON you should see a process " Daemon " by user " event_scheduler ".
  • use SET GLOBAL event_scheduler = ON; to enable the scheduler if it's currently not enabled.
  • More on configuring event scheduler read here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM