Let's say we have a very simple while row query script, for example:
<?php
include('conection.php');
$Verd = 'Verduras';
$smt = $con->prepare("select * from prodcts WHERE Type = :Verduras Order by PrdName ASC");
$smt->bindParam(':Verduras', $Verd, PDO::PARAM_STR);
$smt->execute();
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT))
{
echo '<th>'.nl2br($smr['PrdName']).'</th><th>'.nl2br($smr['SellType']).'</th><th>$'.nl2br($smr['Cost']).'</th>';
}
?>
Question:
How can i make than the results of the $smr['Cost']
Sum it up with the $smr['Cost']
of the rest/some others rows?
Any commentary, suggestion, question for improve the question or any kind of related answer looking to help & improve the question or result in the solution, etc would be much apreciated
Thanks in Advance!
PS: i check for another answers before, but mostly was mysql oriented, nevertheless i wanna check for a PHP more oriented solution, so to have more control about it and try to avoid (if possible) multiple querys.
Before you start the while loop, create a variable. In the while loop increase the variable by the value you want to add. e.g:
$total = 0;
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT))
{
echo '<th>'.nl2br($smr['PrdName']).'</th>
<th>'.nl2br($smr['SellType']).'</th>
<th>$'.nl2br($smr['Cost']).'</th>';
$total += $smr['Cost'];
}
At the end, when you call $total
, it will contain the sum.
<?php echo $total ?>
Hope it helps
If you need the sum of all rows, you can just create a variable before the while...
$Verd = 'Verduras';
$sum = 0;
$smt = $con->prepare("select * from prodcts WHERE Type = :Verduras Order by PrdName ASC");
$smt->bindParam(':Verduras', $Verd, PDO::PARAM_STR);
$smt->execute();
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) {
echo '<th>'.nl2br($smr['PrdName']).'</th><th>'.nl2br($smr['SellType']).'</th><th>$'.nl2br($smr['Cost']).'</th>';
$sum += $smr['Cost'];
}
echo $sum;
But if you need the value grouped $smr['PrdName'], just create a new array..
$Verd = 'Verduras';
$sum = 0;
$smt = $con->prepare("select * from prodcts WHERE Type = :Verduras Order by PrdName ASC");
$smt->bindParam(':Verduras', $Verd, PDO::PARAM_STR);
$smt->execute();
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) {
$prd[$smr['PrdName']][$smr['SellType']][0] += $smr['Cost'];
}
After that, you can display each line with a foreach... It's easily to control using only SQL, but if you need to realize the treatment with PHP, i hope it helps.