Detective merry
Detective merry

Reputation: 394

How to UPDATE and add on top the current value in PHP?

I am a beginner programmer trying to add 'earnings' from table ebaycashback into the existing value of 'cashback' from table Accounts.

ebaycashback enter image description here

Accounts enter image description here

Therefore, I want to add 40 from ebaycashback into Accounts. Problem is, I need the current cashback value from another table, so I have to join two tables together. I am unable to spot whats wrong
Here are my set of codes:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ERROR);
try{
    //Database connection
    $conn = new mysqli("localhost", "xxxxxxxx", "xxxxxxxxx", "xxxxxxxx");

    //select earnings, campaign id and cashback
    $result = $conn->query("SELECT ec.earnings as add, ec.campaignid, ac.cashback as total 
                            FROM ebaycashback ec, Accounts ac 
                            WHERE ec.campaignid = ac.campaignID 
                            GROUP BY ec.campaignID");
 //retrieves and returns the next row assigned to $row
    while($row = $result->fetch_array()){    

 //Add the new cashback into the current balance
    $row['add'] + $row['total'] = $totalcashback;
 //Update Accounts of the new cashback value
    $res = $conn->query("UPDATE Accounts SET cashback = '".$totalcashback."' WHERE campaignid = ".$row['campaignid']);
//Check if $res was executed correctly, doesn't affect the whole code
    if (!$res){ 
    $json_out = "[" . json_encode(array("result"=>0)) . "]";    
    } 
    else { 
    $json_out = "[" . json_encode(array("result"=>1)) . "]"; 
    }

    }
}catch(Exception $e) {
    $json_out =  json_encode(array("result"=>0));
    echo $json_out; 
}
?>

Upvotes: 1

Views: 82

Answers (2)

Detective merry
Detective merry

Reputation: 394

Very weird, it turns out the 'as ...' part is causing the problem, works after I removed them, also changed my $totalcashback formula based on @Oleksandr Kaleniuk answer. Here is the set of codes:

try{
        //Database connection
        $conn = new mysqli("localhost", "seetoh88_m06", "careep21", "seetoh88_m06");

    $result = $conn->query("SELECT earnings, ebaycashback.campaignid, cashback FROM
    ebaycashback, Accounts WHERE ebaycashback.campaignid = Accounts.campaignid");

    while($row = $result->fetch_array()){    
 //Add the new cashback into the current balance
    $totalcashback = $row['earnings'] + $row['cashback'];
 //Update Accounts of the new cashback value
    $res = $conn->query("UPDATE Accounts SET cashback = '".$totalcashback."' WHERE campaignid = ".$row['campaignid']);

    }



}

Upvotes: 0

Oleks
Oleks

Reputation: 1633

It should be:

$totalcashback = $row['add'] + $row['total'];

instead of:

$row['add'] + $row['total'] = $totalcashback;

Upvotes: 2

Related Questions