我想更新属于以下客户的三个发票数据:
function updateInvoice($dbh, $id, $amount, $bal, $payer){
$q = $dbh->query("SELECT * FROM `zinvoice` WHERE `id`='$id'
AND `status` IN ('Balance','Not Paid')");
$nrow = count($q->fetchAll());
$remain = 0;
if($nrow==1){
//update the amount
if($amount>$bal){
$remain = $amount-$bal;
$dbh->query("UPDATE zinvoice SET paidamount=(paidamount+$bal),
balanceamount='0', status='Paid'
WHERE id='$id'");
//payment history update
}else if($amount==$bal){
$remain = 0;
$dbh->query("UPDATE zinvoice SET paidamount=(paidamount+$bal),
balanceamount='0', status='Paid'
WHERE id='$id'");
//payment history update
}else{
$newbal = $bal-$amount;
$dbh->query("UPDATE zinvoice SET paidamount=(paidamount+$amount),
balanceamount='$newbal', status='Balance'
WHERE id='$id'");
$remain = 0;
//payment history update
}
}else{
//Nothing to update Because there is no Invoice with balance or not paid
}
return $remain;
}
现在我想通过客户ID = 2更新多个发票。 id = 2的客户有三张发票,总金额为1500,发票ID = 1金额= 500,发票ID = 2金额= 700,发票ID = 3金额= 300
//Loop to update
$q = $dbh->query("SELECT * FROM zinvoice WHERE customerid='$cid'");
while($row =$q->fetch(PDO::FETCH_OBJ)):
$remain = updateInvoice($dbh, $row->id, $amount, $row->balanceamount, $payer);
if($remain>=1){
updateInvoice($dbh, $row->id, $remain, $row->balanceamount, $payer);
}else{
//nothing
}
endwhile;
$amount would come from a form//amount = 800
$cid would also come from a form//cid = 2
$payer would also come from a form//payer = john
问题是此代码将所有发票更新为status=Paid
。我希望此代码更新余额金额为700的Invoice id=2
,并且剩余100个金额,它会继续更新其他发票,例如Invoice id=3
。但是Invoice id=3
的余额amount=300
大于100 amount
,它会从100
中减去Invoice id=3
而200 balance amount
会{{1}}。并且没有更多的金额,并将停止更新。
我如何实现所需的输出?
注意:我没有使用预准备语句来避免更多代码。这段代码很容易受到sql注入。