I want to update three invoice data that belongs to a customer like below:
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;
}
Now I want to update multiple invoices by a customer id=2. Customer with id=2 has three invoices with total amount of 1500, invoice id=1 has amount=500, invoice id=2 has amount=700, invoice id=3 has amount=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
The problem is that this code updated all the invoices to status=Paid
. I want this code to update Invoice id=2
which has balance amount=700 and as there would be 100 amount remaining, it will continue to update the other invoices, say Invoice id=3
. But Invoice id=3
has a balance amount=300
, which is more than 100 amount
, it will subtract 100
from it and Invoice id=3
would have 200 balance amount
. And there are no more amount left and would stop updating.
How would I achieve my desired output?
Note: I am not using prepared statement to avoid more codes here. And this code would be vulnerable to sql injection.