首页 > 解决方案 > x分钟后在mysqli数据库和php中删除行

问题描述

我正在用 php 创建一个网站。我有一个名为database1我有表的数据库cooldownmy_tablecooldown表包含列time(类型Timestamp默认值CURRENT_TIMESTAMP)和ip(类型 int(30) 默认值none)。在我的代码末尾,我mysqli_query($conn, "DELETE FROM cooldown WHERE time < NOW() - INTERVAL 5 MINUTE");应该在 5 分钟后删除该行,但它不会删除该行。这可能是因为用户被重定向所以 php 脚本停止工作?还是我想念别的东西?

代码:

//Test if it is a shared client
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
  $ip=$_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
}elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
  $ip=$_SERVER['REMOTE_ADDR'];
}
//The value of $ip at this point would look something like: "192.0.34.166"
$ip = ip2long($ip);

//The $ip would now look something like: 1073732954


$query = mysqli_query($conn, "SELECT ip FROM cooldown WHERE ip = '$ip'"); 
$row = mysqli_fetch_array($query); 

if ($row) {
   //What page shall the bans be sent to?
   header("Location: http://imnothere.epizy.com/cooldown.html");   //cooldownpage
   exit();
} else {
    $sql1= "SELECT links FROM my_table WHERE Type = 'spotify' ORDER BY RAND() LIMIT 1";
    $result1 = $conn->query($sql1); //this actually runs the query on the DB, and comes back with a $result object
    if($result1 === false) {
        echo $conn->error();
        }
    $redirect = $result1->fetch_assoc()['links']; //this gets one row from the $result object, and then the 'links' column from that row.
    header("Location: " . $redirect);
    $sql = "INSERT INTO cooldown(ip, time) VALUES('$ip', NOW())";
    $result = $conn->query($sql); //this actually runs the query on the DB, and comes back with a $result object
    if($result === false) {
    }
    mysqli_query($conn, "DELETE FROM cooldown WHERE time < NOW() -  INTERVAL 5 MINUTE");
} 

标签: phpdatabasemysqli

解决方案


您的 SQL 查询不会在 5 分钟后删除行,它会删除请求时 5 分钟或更早的所有内容。

您可能最好将该行代码移动到一个单独的文件中,该文件由您运行cron或在您的数据库中设置一个事件以每分钟左右执行一次。


推荐阅读