mdnba50
mdnba50

Reputation: 379

mysql insert inside foreach loop, cron not working

This code works if i run in a browser. When i run the script via a cron, it doesn't get through the array and stops halfway? Why is this?

$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')";
                }
            }
        }
    }
}

This isn't the exact code as it is too long to post but similar. The code works perfectly in the browser?? running via cron it stops at gbp-jpy? Why is this?

Is there a mysql query limit?

Upvotes: 0

Views: 216

Answers (1)

Barmar
Barmar

Reputation: 780861

Add a unique index on (type, date_time) to the table. Then combine your two queries into 1. Also, use a prepared statement.

$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();
            }
        }
    }
}

Upvotes: 1

Related Questions