【问题标题】:Delete row after x minutes in mysqli database and phpx分钟后在mysqli数据库和php中删除行
【发布时间】:2019-08-30 20:33:14
【问题描述】:

我正在用 php 创建一个网站。我有一个名为 database1 的数据库 我有表 cooldown 和 my_table cooldown 表包含列 time(type Timestamp 默认值 CURRENT_TIMESTAMP) 和 ip(type 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");
} 

【问题讨论】:

  • 您是否希望将来自动安排删除?

标签: php database mysqli


【解决方案1】:

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

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

【讨论】:

  • 或者,您可以删除SELECT ip FROM cooldown WHERE ip = '$ip' 之前的行,这比设置某种异步进程更容易。
【解决方案2】:

您可以使用 Cron 作业、主管或安排时间 你的 SQL 查询几乎和它一样


DELETE FROM cooldown WHERE time < NOW() - INTERVAL 5 MINUTE

如果您希望每五分钟一次,请使用任一


*/5 * * * *  fooo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2013-06-10
    • 2016-05-09
    • 2016-06-09
    • 2012-09-28
    相关资源
    最近更新 更多