简体   繁体   English

如何每天使用Cron Jobs将行插入数据库中?

[英]How can I insert rows into my DB daily using Cron Jobs?

I have this Cron Job that I want to run once a day. 我有这个Cron Job,我想每天运行一次。 It checks to see if it's a new day, and if it is, it inserts a new row into my database table. 它检查是否是新的一天,如果是新的一天,它将在我的数据库表中插入新的一行。 I use this to keep track of the daily sales for each item on my online store. 我用它来跟踪在线商店中每个商品的每日销售额。

  • I also need it to grab the day from the last row for that product_id, increment it by 1 and then include it in my INSERT query. 我还需要它从该product_id的最后一行获取day ,将其递增1,然后将其包含在我的INSERT查询中。 This is so that I can easily keep track of the current day for each product. 这样一来,我可以轻松跟踪每种产品的当天。

  • The MAX(time_stamp) is also illegal code, however I don't know what to replace it with. MAX(time_stamp)也是非法代码,但是我不知道用什么替换它。 I use it to select the latest day for each item, so that the Cron Job doesn't select every single row. 我用它来选择每个项目的最新日期,以使Cron Job不会选择每一行。

I've never used Cron Jobs before, meaning that I'm a noob so please be easy on me :) 我以前从未使用过Cron Jobs,这意味着我是一个菜鸟,所以请对我放心:)

Thanks for the help! 谢谢您的帮助! :) :)

Here's my code: 这是我的代码:

PHP: PHP:

// Checks if past a day
$days = DB::fetch("SELECT * FROM `daily_sales` WHERE MAX(time_stamp)<=CURRENT_DATE - INTERVAL 1 DAY;");
$numrows = count($days);

// If there is a new day
if ($numrows > 0) {
    foreach ($days as $i => $day) {
        // Adds a fresh day with 0 sales
        $sales = 0;
        $product_id = $day->product_id;
        $day = // Get the day from the last row, and add 1
        $time_stamp = time();
        DB::query('INSERT INTO `daily_sales` (`product_id`, `sales`, `day`, `time_stamp`) VALUES (?, ?, ?, ?);', array($product_id, $sales, $day, $time_stamp));
    }
}

daily_sales : (the DB table) daily_sales :(数据库表)

id | product_id | day | time_stamp | sales

you have to open cron job, add new job and define 您必须打开cron作业,添加新作业并定义

how to open cron tab 如何打开cron选项卡

crontab -e

add following to your cron tab 将以下内容添加到您的cron标签中

0 0 * * * php /full/path/to/script.php

OR 要么

you can use mysql triggers http://www.mysqltutorial.org/mysql-triggers.aspx that will allow you to make "audit" table which will contain daly sales. 您可以使用mysql触发器http://www.mysqltutorial.org/mysql-triggers.aspx ,该触发器可让您制作包含每日销售额的“审核”表。 So you can insert/update audit table by using "after insert". 因此,您可以使用“插入后”来插入/更新审核表。

hope this will help 希望这会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM