I've got a function which calculates some data from a table, a put's it into another, it takes a while for the whole process, about 30 mins or something like that. The function calculates statistics for each day for a couple of months period, but after like 10 days, it starts another thread while continuing another one, and then another one, and another, so i get a table full of random crap in the end.
Why does it start another instance of the function while the other one isn't finished?
Here's the function:
function build_fill_array() {
$sql = db_fetch_object(db_query("SELECT min(timestamp) as min FROM {accesslog}"));
$nids = db_query("SELECT nid FROM {node} WHERE type='raamat'");
while($nid_array = db_fetch_array($nids)) {
$nid[] = $nid_array['nid'];
}
$start_ts = $sql->min;
$end_ts = mktime(0,0,0, date('m'), date('d'), date('Y'));
$start_ts = mktime(0,0,0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
while($start_ts != $end_ts) {
$day = date('d.m.Y', $start_ts);
$range_from = mktime(0,0,0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
$range_to = mktime(23,59,59, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
foreach($nid as $n) {
$results = db_fetch_object(db_query("SELECT count(hostname) as total, count(distinct hostname) as visits FROM {accesslog} WHERE timestamp BETWEEN %d AND %d AND path = 'node/%d'", $range_from, $range_to, $n));
$sql_insert = "INSERT INTO {statistics_view} (`id`, `nid`, `total`, `unique`, `timestamp`, `date`) VALUES (NULL, $n, $results->total, $results->visits, ".mktime().", '$day');";
db_query($sql_insert);
}
$start_ts = mktime(0,0,0, date('m', $start_ts), date('d', $start_ts)+1, date('Y', $start_ts));
}
}
Edit: don't mind the {} around table names, it's a drupal thing.