Reputation: 78
i like to sum all row values from the $orderfeed_query. But when i echo the $sum, i get just the sum from the last loop.
how can can i add the sum of all following loop on the $sum variable? I dont know how many loops a order have.
$checkorder = mysql_query("SELECT * FROM orders WHERE `email` = '$email' ") or die(mysql_error());
while ($row = mysql_fetch_assoc($checkorder)) {
$orderid = $row["orderid"];
$check_order = $row["check_order"];
if($check_order[0] == 1){
$orderfeed_query = mysql_query("SELECT * FROM orderfeed WHERE `orderid` = '$orderid' AND `product` = '1'") or die(mysql_error());
while ($row = mysql_fetch_assoc($orderfeed_query)) {
$signaturewiz = $row["signaturewiz"];
$flurstueckwiz = $row["flurstueckwiz"];
$uploadwiz = $row["uploadwiz"];
$exsignaturewiz = $row["exsignaturewiz"];
$ibanwiz = $row["ibanwiz"];
$sum = $signaturewiz+$flurstueckwiz+$uploadwiz+$exsignaturewiz+$ibanwiz;
echo $sum;
}
}
}
}
Upvotes: 0
Views: 60
Reputation: 94682
Move the echo of $sum
outside the loop
Use +=
rather than +
to accumulate a total over multiple iterations
Initialize your variable before using +=
as if $sum
has an undefined value it can mess up the count when using +=
$sum = 0; // init variable
while ($row = mysql_fetch_assoc($orderfeed_query)) {
$signaturewiz = $row["signaturewiz"];
$flurstueckwiz = $row["flurstueckwiz"];
$uploadwiz = $row["uploadwiz"];
$exsignaturewiz = $row["exsignaturewiz"];
$ibanwiz = $row["ibanwiz"];
$sum += $signaturewiz + $flurstueckwiz + $uploadwiz +
$exsignaturewiz + $ibanwiz;
}
echo $sum;
ADDITIONAL INFO:
You see 12 and not 3 so the data from your table I assume is text and not numeric so do this to convert text numbers to integers
$sum = 0; // init variable
while ($row = mysql_fetch_assoc($orderfeed_query)) {
$signaturewiz = (int)$row["signaturewiz"];
$flurstueckwiz = (int)$row["flurstueckwiz"];
$uploadwiz = (int)$row["uploadwiz"];
$exsignaturewiz = (int)$row["exsignaturewiz"];
$ibanwiz = (int)$row["ibanwiz"];
$sum += $signaturewiz + $flurstueckwiz + $uploadwiz +
$exsignaturewiz + $ibanwiz;
}
echo $sum;
Upvotes: 1
Reputation: 2104
Several people have pointed out that $sum
should be outside the loop, and that is indeed correct. However, MySQL can do this all for you:
$orderfeed_query = mysql_query("SELECT SUM(signaturewiz + flurstueckwiz + uploadwiz + exsignaturewiz + ibanwiz) FROM orderfeed WHERE orderid = '$orderid' AND product = '1'") or die(mysql_error());
if ($row = mysql_fetch_row($orderfeed_query)) {
echo $row[0];
}
Upvotes: 1
Reputation: 4220
This code
$sum = $signaturewiz + $flurstueckwiz + $uploadwiz + $exsignaturewiz + $ibanwiz;
overwrites sum each time. You must add to sum not to overwrite
$sum += $signaturewiz + $flurstueckwiz + $uploadwiz + $exsignaturewiz + $ibanwiz;
And declare $sum = 0;
before main loop
Upvotes: 1