如何每24小时php cronjob在数据库中存储值

时间:2017-05-29 19:24:26

标签: php mysqli cron

我正在运行带有cronjob的脚本每24小时运行一次脚本,但是当我刷新页面时它也会出现更新问题,我希望运行指定的时间运行脚本。

使用以下代码

$dif = time();

if ($dif < time()+1) {

$conn = mysqli_connect("localhost", "root", "", "bitmining");
$test = "Hello";
$las_d = date("y-m-d");
$sql3 = "INSERT INTO php_cron(last_ts, value) VALUES('$las_d','$test')";
    mysqli_query($conn, $sql3);
    echo "Updated!";
}

我是php新手,任何人都可以帮我解决这个问题

2 个答案:

答案 0 :(得分:0)

每次执行CRON时,在DB中解决此存储日期。

在插入之前检查它。

<?php
$conn = mysqli_connect("localhost", "root", "", "bitmining");
$dif = time();
$date = "SELECT date_insert FROM php_cron ORDER BY date ASC LIMIT 1";
//84300 are 24h in seconds.
if ($date+84300 > time()){
    if ($conn){
        $sql3 = "INSERT INTO php_cron(last_ts, value, date_insert) VALUES('$las_d','$test','".time()."')";

        if (mysqli_query($conn, $sql3))
        {
            echo "Updated!";
        }
        else
        {
            echo "There is an error.";
        }
    }
}
else {
echo "Not yet!";
}
?>

答案 1 :(得分:0)

我认为这只会复制。 我们来试试吧!

 <?php
$conn = mysqli_connect("localhost", "root", "", "stacks");
$dif = time();
$sql = "SELECT date_insert FROM php_cron ORDER BY date_insert DESC LIMIT 1";
$old_date = mysqli_query($conn, $sql);
if ($old_date->num_rows > 0) {
    $older_date = $old_date->fetch_assoc()['date_insert'];
    $now_date = date_create(date('Y-m-d H:i:s'));
    $old_timestamp = date_create(date( "Y-m-d H:i:s", strtotime( $older_date ) ));
    $diff=date_diff($old_timestamp,$now_date);

    if ($diff->days >= 1){
        if ($conn){
            $las_d = "Input here your values";
            $test = "Input here your values";
            $now_date_updated = date('Y-m-d H:i:s');
            $sql3 = "INSERT INTO php_cron(last_ts, value, date_insert) VALUES('".$las_d."','".$test."','".$now_date_updated."')";

            if (mysqli_query($conn, $sql3))
            {
                echo "Updated!";
            }
            else
            {
              echo "There is an error.";
            }
        }
    }
    else {
    echo "Not yet!";
    }
}

?>