I am trying to write a foreach loop that will send a separate report by mail for each array element, but it keeps outputting the last element only. I've tried writing this so many ways that I think I'm starting to repeat myself. Please help.
$items = array(1 => 1, 2 => 2, 3 => 3, 7 => 4, 8 => 5,9 => 6, 17 => 8, 18 => 338, 19 => 50, 23 => 52, 11 => 7, 16 => 44, 4 => 11, 5 => 22, 6 => 33);
foreach ($items as $id => $number) {
//I am querying a pervasive database here
$wtdVar = $dbx->getOne('SELECT SUM(sales) FROM table WHERE date1 >= '.$wkstart3.' AND date2 <= '.$today3.' AND category <> \'ABC\' AND number = '.$number);
if (DB::isError($wtdVar)) {
echo '<div class="error">Error: - '.$wtdVar->getDebugInfo().'</div>';
}
//get the goal for the week so far, use date variables with 2 at the end for postgres queries
$wtdgoal = $db->getOne("SELECT SUM(goal) FROM table2 WHERE id = $id AND gdate BETWEEN '$wkstart2' AND '$today2'");
if (DB::isError($wtdgoal)) {
echo '<div class="error">Error: - '.$wtdgoal->getDebugInfo().'</div>';}
}
There are 15 items in the array, and the e-mail of the report works just fine, but the data in the report is the last item 15x. There are more data, and with a static variable where I have the array elements it works perfectly, but I need it to loop because I have to use this data at many places.
You need to set up arrays to contain all your retrieved values.
$wtdVars = array();
$wtdgoals = array();
foreach ($items as $id => $number) {
//I am querying a pervasive database here
$wtdVar = $dbx->getOne('SELECT SUM(sales) FROM table WHERE date1 >= '.$wkstart3.' AND date2 <= '.$today3.' AND category <> \'ABC\' AND number = '.$number);
$wtdVars[] = $wtdVar;
if (DB::isError($wtdVar)) {
echo '<div class="error">Error: - '.$wtdVar->getDebugInfo().'</div>';
}
//get the goal for the week so far, use date variables with 2 at the end for postgres queries
$wtdgoal = $db->getOne("SELECT SUM(goal) FROM table2 WHERE id = $id AND gdate BETWEEN '$wkstart2' AND '$today2'");
$wtdgoals[] = $wtdgoal;
if (DB::isError($wtdgoal)) {
echo '<div class="error">Error: - '.$wtdgoal->getDebugInfo().'</div>';
}
}
Then presumably in your report you have a loop that keeps using $wtdVar
or $wtdgoal
- instead this should use $wtdVars[$i]
and $wtdgoals[$i]
where $i
is a variable starting at zero that increments with each iteration of the loop in the report.