1

正如您从下表中看到的,ID 为 1 的用户总共有 10 分
我想要做的是从表单提交一个数字$edit_points以循环并从用户 1 中减去
这个数字可以是任何东西,例如:

$edit_points = 6
将从第一条记录中减去 4,
然后移至下一条,仅减去余数 2
,然后跳出循环

UserID  | TotalPoints      
-------------------
 1      | 4        
 1      | 4      
 1      | 2      
 4      | 3        
 3      | 3       
 5      | 4      

这是我到目前为止所拥有的

$pointLeft = $edit_points;//sent from form    
while($point = mysqli_fetch_array($output)){

if($pointLeft > $point["TotalPoints"]){//if pointsLeft more than this record
$remainder =  $pointLeft-$point["TotalPoints"];//get remainder
$query2 = "UPDATE pointstable SET TotalPoints=0 WHERE UserID=".$UserID;
$output2 =  $mysqli->query($query2);

}elseif($pointLeft < $point["TotalPoints"]){

$remainder =  $point["TotalPoints"] - $pointLeft;   
$query2 = "UPDATE pointstable SET TotalPoints=".$remainder." WHERE UserID=".$UserID;
$output2 =  $mysqli->query($query2);

}

$pointLeft = $remainder;

}

它工作到一定程度,似乎用与剩余相同的最后一个值填充所有记录,我尝试过 break 并将 if ($pointLeft<=0) 放在第一个 if
但没有工作。
有什么帮助吗?或者更好的方法,最好使用 php

4

1 回答 1

0

感谢 Marty
修改了下面的代码
有一个我现在使用的唯一 id PointID

$poinstLeft = $edit_points; //sent from form

while($point = mysqli_fetch_array($output)){
    //if pointsLeft more than this record
    if($poinstLeft >= $point["TotalPoints"]){
        //get remainder
        echo $poinstLeft." ";
        $remainder =  $poinstLeft-$point["TotalPoints"];
        $query2 = "UPDATE pointstable SET TotalPoints=0 WHERE UserID=".$UserID." AND PointID=".$point["PointID"];

        $output2 =  $mysqli->query($query2);
        // Calculate new pointsleft
        $poinstLeft = $remainder;

    } elseif ($poinstLeft < $point["TotalPoints"]){
        $remainder =  $point["TotalPoints"] - $poinstLeft;
        echo $poinstLeft." ";
        $query2 = "UPDATE pointstable SET TotalPoints=".$remainder." WHERE UserID=".$UserID." AND PointID=".$point["PointID"] ;
        $output2 =  $mysqli->query($query2);
        // Here, your remainder is different from the upper half of your if-function!
        // So, you don't have to recalculate pointsleft... It's just:
        $poinstLeft = 0;

        // Break the while loop:
     break 2;
    }


}
于 2013-09-04T21:08:04.720 回答