How to sum mysql values in multple while PHP - php

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;
}
}
}
}

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

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];
}

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;

Related

Decimals For negative PHP values

I am writing a bit of php code to output a random value
$max_mal = (3 - $oray);
$oray = 1;
$max = 100;
$total = 0;
for ($i = 0; $i < $max_mal; $i++){
$goli = mt_rand(3, 8);
$total += $goli;
$golis[] = $goli;
}
and for each loop goes here
foreach($golis as &$goli) {
$goli = floor(($goli / $total) * $max);
if ($goli == 0) {
$goli = 1;
}
}
$result = array_pad($golis, 3, -1);
shuffle($result);
$myresult = $result[0];
I am looking to get decimal values upto 5 numbers, but once a negative value comes it results out as 0.000-1 instead of -0.00001
$myresultb = str_pad($mario, 5, '0', STR_PAD_LEFT);
$myresultf = '0.'.$myresultb.'<br/>';
$total_score = 300;
echo $myresultf;
Secondly I am new to php learning so am I doing this PHP correct or it needs improvement
I have a div to show total score like this
<div id="total_score"></div>
and another div to show current score which value comes as echo $myresultf;
<div id="current_score"></div>
I want to update total score in real time with jquery wheneven button is clicked and <?php echo $myresultf ?> is refreshed in real time also
$("#play").click(function() {
var currentscore = $("#current_score").val();
var totalscore = $("#total_score").val();
how to do this.....
});
Try this:
$max = 100;
$oray = 1;
$max_mal = (3 - $oray);
$total = 0;
for ($i = 0; $i < $max_mal; $i++){
$goli = mt_rand(3, 8);
$total += $goli;
$golis[] = $goli;
}
foreach($golis as &$goli) {
$goli = floor(($goli / $total) * $max);
if ($goli == 0) {
$goli = 1;
}
}
$result = array_pad($golis, 3, -1);
shuffle($result);
$myresult = $result[0];
$negative_var=false;
if($myresult < 0)
{
$negative_var=true;
$myresult = 0-$myresult;
}
$myresultb = str_pad($myresult, 5, '0', STR_PAD_LEFT);
$myresultf = '0.'.$myresultb.'<br/>';
if($negative_var)
$myresultf="-".$myresultf;
$total_score = 300;
echo $myresultf;
simple use as follow:
$myresultb =str_replace('-','',$myresultb);
if($myresult == -1) {
$myresultf = '-0.'.$myresultb.'<br/>';
}
else {
$myresultf = '0.' . $myresultb . '<br/>';
}

Show lowest value in a select

I am trying to get 1 result of the lowest value from a set. So I have a set of number (averages) i just need to show the lowest one of the set:
if ($danresult->num_rows > 0) {
while($row = $danresult->fetch_assoc()) {
$score1 = $row["score_1"];
$score2 = $row["score_2"];
$score3 = $row["score_3"];
$score4 = $row["score_4"];
$score5 = $row["score_5"];
$score6 = $row["score_6"];
$score7 = $row["score_7"];
$score8 = $row["score_8"];
$sum = $score1 + $score2 + $score3 + $score4 + $score5 + $score6 + $score7 + $score8;
$totalAverage = $sum / 8;
$totalAverages[] = $totalAverage;
$index = min($totalAverages);
echo $index . '<br>';
}
}
I have been trying to use the php min() function to no avail!
My results would typically be like 2, 2.75, 3, 3.35 etc.. so I just need to show the lowest of the set. so like 2 from the set above.
you could add all values to an array and use the array functions to determine the winner
if ($danresult->num_rows > 0) {
while($row = $danresult->fetch_assoc()) {
$scores=array(
$row["score_1"],
$row["score_2"],
$row["score_3"],
$row["score_4"],
$row["score_5"],
$row["score_6"],
$row["score_7"],
$row["score_8"]
);
$sum= array_sum ($scores);
$totalAverage = $sum / count($scores);
$min=min($scores);
$winner=array_search($min, $scores);
}
}
Try this, you need to close foreach...then get a lowest value from array
if ($danresult->num_rows > 0) {
while($row = $danresult->fetch_assoc()) {
$score1 = $row["score_1"];
$score2 = $row["score_2"];
$score3 = $row["score_3"];
$score4 = $row["score_4"];
$score5 = $row["score_5"];
$score6 = $row["score_6"];
$score7 = $row["score_7"];
$score8 = $row["score_8"];
$sum = $score1 + $score2 + $score3 + $score4 + $score5 + $score6 + $score7 + $score8;
$totalAverage = $sum / 8;
$totalAverages[] = $totalAverage;
}
$index = min($totalAverages);
echo $index . '<br>';
}

Retrieve All Data From One Table in Database into Array and Calculate it

Related to question from this Pearson correlation in PHP , now I'm using that function too for calculate similarity between 2 users with pearson correlation. What I wanna ask is :
I have database name ta_db
And I want to retrieve data from table interest which have 9 attributes into array
After that I want to calculate it with pearson correlation function.
public function similarity($user1, $user2) {
$sharedItem = array();
$pref1 = array();
$pref2 = array();
$result1 = $user1->fetchAllPreferences();
$result2 = $user2->fetchAllPreferences();
foreach($result1 as $pref){
$pref1[$pref->item_id] = $pref->rate;
}
foreach($result2 as $pref){
$pref2[$pref->item_id] = $pref->rate;
}
foreach ($pref1 as $item => $preferenza){
if(key_exists($item,$pref2)){
$sharedItem[$item] = 1;
}
}
$n = count($sharedItem);
if ($n == 0) return 0;
$sum1 = 0;$sum2 = 0;$sumSq1 = 0;$sumSq2 = 0;$pSum = 0;
foreach ($sharedItem as $item_id => $pre) {
$sum1 += $pref1[$item_id];
$sum2 += $pref2[$item_id];
$sumSq1 += pow($pref1[$item_id],2);
$sumSq2 += pow($pref2[$item_id],2);
$pSum += $pref1[$item_id] * $pref2[$item_id];
}
$num = $pSum - (($sum1 * $sum2) / $n);
$den = sqrt(($sumSq1 - pow($sum1,2)/$n) * ($sumSq2 - pow($sum2,2)/$n));
if ($den == 0) return 0;
return $num/$den;
}
From my explanation above, could you please tell me how to retrieve the data into Array? Thank you in advance for your help and clear explanation.

wrong results: sum of two variables

I have a simple problem, but I can't solve it, still.
Working code
(int)$sum_price=4;
(int)$price_per_sum = (int)$spo[$key]*(int)$gpp['price'];
echo $sum_price = ($sum_price + $price_per_sum);
When I change 4 to a variable, the result of sum() is string.
Result becomes a string
$spo[$key] = 1;
$gpp['price'] = 2;
(int)$sum_price=4;
(int)$price_per_sum = (int)$spo[$key]*(int)$gpp['price'];
echo $sum_price = ($sum_price + $price_per_sum);
The result is 42 but should be 6, instead. Using (int) does not change my result.
Problem code
# Get All Payment
(int)$sum_price = 0;
$sum_price_product = explode('|',$_SESSION['product']);
$spo = explode('|',$_SESSION['order']);
foreach($sum_price_product as $key=>$spp)
{
if($spp!='')
{
$get_product_price = $dbc->select("sh_product"," id = '{$spp}'","id");
$gpp = mysql_fetch_array($get_product_price['sql']);
(int)$price_per_sum = $spo[$key] * $gpp['price'];
$sum_price = $sum_price + $price_per_sum;
echo $sum_price;
}
}
http://codepad.org/Zo9X2PY5
Type Casting is not necessary in this case...
And please put the right associative array key its "price"or 'price' not just price...
$sum_price = 4;
$price_per_sum = $spo[$key] * $gpp['price'];
$sum_price = ($sum_price + $price_per_sum);
echo $sum_price;
And your Example :
$spo[$key] = 1;
$gpp['price'] = 2;
$sum_price = 4;
$price_per_sum = $spo[$key] * $gpp['price'];
$sum_price = ($sum_price + $price_per_sum);
echo $sum_price;
# Get All Payment
(int)$sum_price=0;
$sum_price_product = explode('|',$_SESSION['product']);
$spo = explode('|',$_SESSION['order']);
foreach($sum_price_product as $key=>$spp)
{
if($spp!='')
{
$get_product_price = $dbc->select("sh_product"," id = '{$spp}'","id");
$gpp = mysql_fetch_array($get_product_price['sql']);
(int)$price_per_sum = $spo[$key]*$gpp['price'];
$sum_price = $sum_price + $price_per_sum;
echo $sum_price;
}
}
Casting is not required in this case. Please review below code and try it out,its working for me:
$spo[0] = 1;
$gpp['price'] = 2;
$sum_price=4;
$price_per_sum = $spo[0]*$gpp['price'];
$sum_price = $sum_price + $price_per_sum;
echo $sum_price;
Here in $spo[0], i have considered single value but you can replace '0' by $key in loop construct.
Please review here my working code: http://codepad.org/zH2q2WjH

Array counting with different keys

What I need is putting this array in a loop, but I can't get it to work because week is 1 - 9 and the key is 0 - 8. So i getting a error with a undefined offset i know why the does that but I don't know how to do this properly.
Before people ask me why not just change week1 to week0 and start counting from there. I can't because I did a calculating that is based on 1 - 52 and it will mess up my calculating if I start on 0 - 51
$totaal_vruchtzetting_week[10] = $totaal["week1"][0] + // = 0.46
$totaal["week2"][1] + // = 2.87
$totaal["week3"][2] + // = 4.97
$totaal["week4"][3] + // = 4.35
$totaal["week5"][4] + // = 3.02
$totaal["week6"][5] + // = 2.03
$totaal["week7"][6] + // = 1.41
$totaal["week8"][7] + // = 1.12
$totaal["week9"][8]; // = 1.13
// Should be total 21,36
Edit:
This is my loop I got until now but it gives me the wrong answer plus 2 errors
for($week = 1; $week < 9; $week++)
{
for($sw = 0; $sw <= 8; $sw++)
{
$totaal_vruchtzetting_week[10] += $totaal["week".$week][$sw];
}
}
echo $totaal_vruchtzetting_week[10]; // Outputs 170.89
$i=1;
$totaal_vruchtzetting_week[10]=0;
foreach($totaal as $total)
{
$totaal_vruchtzetting_week[10]+=$total["week$i"][$i-1];
$i++;
}
echo $totaal_vruchtzetting_week[10];
You should sum with this this loop
$i = 1;
$result = 0;
for ($i = 1; $i <= 9; $i++) {
if (isset($totaal['week' . $i]) && isset($totaal['week' . $i][$i - 1])) {
$result += floatval($totaal['week' . $i][$i - 1]);
}
}
$totaal_vruchtzetting_week[10] = $result;
$sum = 0;
foreach(array_values($totaal) as $index=>$item)
$sum += reset($item);
echo $sum; // 21.36
$totaal_vruchtzetting_week[10] = $sum;
Demo
Not sure if I got your question, but did you consider foreach? It iterates over every array regardless of the keys.

Categories