简体   繁体   English

如何在午夜从表中删除mysql数据?

[英]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.我有一个 mysql 表,我希望它在每晚午夜“清空”。 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 获取当前时间,然后运行 ​​if 语句,看看它是否等于午夜,以及是否要执行删除信息的 php 脚本。

Javascript: 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:

<?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.我已经通过将 if 语句中的时间设置为比我的实际时间早几分钟的时间对此进行了测试,但它不起作用。

Implementing your own event scheduler, especially as a web page using JavaScript is a bad idea.实现您自己的事件调度程序,尤其是作为使用 JavaScript 的网页是一个坏主意。 Use for that either用于那个

  • a cron job to run DELETE statement through the mysql command line interface通过 mysql 命令行界面运行DELETE语句的cron作业
    /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:如果您使用 MySQL 事件方法:

  • use SHOW PROCESSLIST to check if the event scheduler is enabled.使用SHOW PROCESSLIST检查是否启用了事件调度程序。 If it's ON you should see a process " Daemon " by user " event_scheduler ".如果它打开,您应该看到用户“ event_scheduler ”的进程“ Daemon ”。
  • use SET GLOBAL event_scheduler = ON;使用SET GLOBAL event_scheduler = ON; to enable the scheduler if it's currently not enabled.如果当前未启用,则启用调度程序。
  • More on configuring event scheduler read here有关配置事件调度程序的更多信息,请阅读此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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