dph23577 2013-12-12 02:25
浏览 11
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • donglian4464 2013-12-12 02:27
    关注

    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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊