从下表中可以看出,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&lt; = 0)放在第一个if上面 但都没有效果 任何帮助?或者更好的方法,最好使用php
答案 0 :(得分: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;
}
}