如何在PHP中更新并添加当前值?

时间:2017-01-23 13:11:51

标签: php

我是一名初学程序员,试图将表ebaycashback中的“收入”添加到表格帐户的“现金返还”现有价值中。

ebaycashback enter image description here

帐户 enter image description here

因此,我想将ebaycashback中的40添加到Accounts中。问题是,我需要来自另一个表的当前返现值,所以我必须将两个表连接在一起。我无法发现什么是错的 这是我的一组代码:

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

2 个答案:

答案 0 :(得分:2)

应该是:

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

而不是:

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

答案 1 :(得分:0)

非常奇怪,事实证明,&#39; as ...&#39;部分导致问题,我删除它后工作,也改变了基于@Oleksandr Kaleniuk答案的$ totalcashback公式。 这是一组代码:

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']);

    }



}