mysql插入foreach循环内部,cron无法正常工作

时间:2017-06-14 23:12:57

标签: php mysql cron

如果我在浏览器中运行,此代码有效。当我通过cron运行脚本时,它没有通过数组并中途停止?这是为什么?

$url_array = array("eur-gbp","eur-aud","usd-chf","eur-usd","eur-jpy","gbp-jpy","eur-cad","eur-chf","usd-cad","usd-jpy","cad-chf","cad-jpy","gbp-usd","aud-usd","gbp-chf","chf-jpy","gbp-cad","aud-cad","aud-chf","aud-jpy","aud-nzd","eur-nzd","gbp-aud","gbp-nzd","nzd-chf","nzd-usd","nzd-cad","nzd-jpy");
$option_array = array(1,2,3,4,5,6,7);

$type_array = array(1,2,3,4,5,6);

foreach($url_array as $url_type) {
    //code
    foreach($option_array as $option) {
        //code
        foreach($duration_array as $duration) {
            //code
            foreach($type_array as $type) {
                //mysql insert

                $sql = "SELECT * FROM `data_analysis` WHERE date_time='".$date."' AND type='".$url_type."' LIMIT 1";
                $query = $this->db->query($sql);

                $result = $query->fetch_assoc();

                if($result){
                    $sql = "UPDATE `data_analysis` SET value='".$percentage."', price_change='".$price."', parent='1' WHERE date_time='".$date."' AND type='".$url_type."'";
                } else {
                    $sql = "INSERT IGNORE INTO `data_analysis` (date_time,value,price_change,type,parent) VALUES ('".$date."','".$percentage."','".$price."','".$url_type."','1')";
                }
            }
        }
    }
}

这不是确切的代码,因为它太长而无法发布但相似。代码在浏览器中完美运行?通过cron运行它在gbp-jpy停止?这是为什么?

是否存在mysql查询限制?

1 个答案:

答案 0 :(得分:1)

(type, date_time)上向表中添加唯一索引。然后将两个查询合并为1.另外,使用预准备语句。

$stmt = $this->db->prepare("
    INSERT INTO data_analysis (date_time, value, price_change, type, parent)
    VALUES (?, ?, ?, ?, '1')
    ON DUPLICATE KEY UPDATE value = VALUES(value), price_change = VALUES(price_change), parent = VALUES(parent)");

$stmt->bind_param("ssss", $date, $percentage, $price, $url_type);

foreach($url_array as $url_type) {
    //code
    foreach($option_array as $option) {
        //code
        foreach($duration_array as $duration) {
            //code
            foreach($type_array as $type) {
                //mysql insert
                $stmt->execute();
            }
        }
    }
}