Delete MySQL Row after 30 minutes using Cron Jobs/

2019-03-03 19:56发布

问题:

I am quite the noob at MySQL and PHP/Cron Jobs so if you all could explain it easily as in where to put the event, etc, that'd be great, anyways, on with the question.

Question: I have a table called my_Table and it has an entry with 3 fields: name,age,timestamp. So one row has this for instance. Sam | 20 | whateverthetimeis. Now, when that row reaches 30 minutes old, I want it to be deleted, same with any other rows that hit 30 minutes, thank you all for the help, I have read the other answers but like I said I'm still a beginner and dont quite understand what people are answering. Thanks for the help

If I can do this with a Cron Job or a MySQL Event (I don't know how to set an event up) it would be great for anyone to help! :D

My code for deleting after 30 minutes (Deletes all rows even when they aren't 30 minutes old)

<?php
include_once('../config.php');

$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);



$runpurge = mysql_query ("DELETE FROM my_table WHERE timestamp < NOW() - INTERVAL 30 MINUTE");






?>

the main display code:

$result = mysql_query ("SELECT * FROM cw_LFG ORDER BY `time` DESC ") or die(mysql_error);



while ($row=mysql_fetch_array($result)) {

    echo "<tbody>";
    echo "<tr><td>";
    echo strip_tags($row['cname']);
    echo "</td><td>";
    echo $row['level'];
    echo "</td><td>";
    echo strip_tags($row['region']);
    echo "</td><td width='100px'>";
    echo timeElapsed(strtotime($row['time']));
    echo "</td><td style='word-wrap: break-word'>";
    echo strip_tags($row['comment']);
    echo "</td></tr>";
    echo "</tbody>";



}

echo "</table>";
$curtime = date('Y-m-d H:i:s');
$curtimestr = strtotime($curtime);
function timeElapsed($time) {
    $elapsedTime = time() - $time;

    if ($elapsedTime < 1) {
        return 'Right now';
    }
    if ($elapsedTime < 60){
        return '< 1 Minute ago';
    }

回答1:

The SQL would be

DELETE FROM my_table
WHERE timestamp < NOW() - INTERVAL 30 MINUTE

Write a PHP script that executes this SQL, and add a crontab entry that runs it every 30 minutes. Or use the MySQL Event Scheduler to run it periodically; it is described here.



标签: php mysql cron row