如何在午夜从表中删除mysql数据? [英] How to delete mysql data from table at midnight?

查看:42
本文介绍了如何在午夜从表中删除mysql数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 mysql 表,我希望它在每晚午夜清空".我在网上搜索了一个答案,但没有发现任何似乎对我有帮助的答案.我有这个想法,使用 javascript 获取当前时间,然后运行 ​​if 语句,看看它是否等于午夜,是否要执行删除信息的 php 脚本.

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:

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';
            });
    };
};

删除.php:

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

我已经通过将 if 语句中的时间设置为比我的实际时间早几分钟的时间对此进行了测试,但它不起作用.

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.

推荐答案

实现您自己的事件调度程序,尤其是在使用 JavaScript 的网页时是个坏主意.用于那个

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

  • a cron 作业通过 mysql 命令运行 DELETE 语句线路接口
  • 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"

  • MySQL 事件,例如立>

         CREATE EVENT delete_messages_at_midnight 
         ON SCHEDULE EVERY 1 DAY STARTS CURDATE() + INTERVAL 1 DAY
         DO DELETE FROM messages;
    

    如果您使用 MySQL 事件方法:

    If you go with MySQL event approach:

    • 使用 SHOW PROCESSLIST 来检查事件调度程序是否已启用.如果它打开,您应该看到用户event_scheduler"的进程Daemon".
    • 使用 SET GLOBAL event_scheduler = ON; 启用调度程序(如果当前未启用).
    • 有关配置事件调度程序的更多信息,请阅读此处
    • 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

    这篇关于如何在午夜从表中删除mysql数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆