Reputation: 83
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.
Upvotes: 1
Views: 2385
Reputation: 92795
Implementing your own event scheduler, especially as a web page using JavaScript is a bad idea. Use for that either
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:
SHOW PROCESSLIST
to check if the event scheduler is enabled. If it's ON you should see a process "Daemon
" by user "event_scheduler
".SET GLOBAL event_scheduler = ON;
to enable the scheduler if it's currently not enabled.Upvotes: 9