I have a running PHP program which handles supplies inventory.
I want this code to process faster to update supplies' balances when opening the page.
SUPPLIES contains the inventory of supplies and their balances.
TRANSACTIONS contains the transactions of receive, return and issued.
The program below retrieves tables' SUPPLIES and TRANSACTIONS and computes the balances from all TRANSACTIONS which updates the MYSQL table of SUPPLIES.
<?php
//Update supplies balance starts here
$supplies = DB::getInstance()->query("SELECT * FROM supplies ORDER BY id DESC");
foreach($supplies->results() as $supply) {
$balance = 0;
$transactions = DB::getInstance()->query("SELECT * FROM transactions ORDER BY id ASC");
foreach($transactions->results() as $transaction) {
if($transaction->code === $supply->id){
if($transaction->transaction_type === "1"){
$balance = $balance + $transaction->quantity;
} else if($transaction->transaction_type === "2"){
$balance = $balance - $transaction->quantity;
} else if($transaction->transaction_type === "3"){
$balance = $balance + $transaction->quantity;
}
}
}
$supplied = new Supply();
$supplied->find($supply->id);
try {
$supplied->update(array(
'balance' => $balance,
));
} catch (Exception $e) {
die($e->getMessage());
}
}
//Update supplies balance ends here
?>
transactionstable once for every single entry in thesuppliestable. Your biggest speed improvement would be to set$transactionsoutside of your$supplies->results()loop.