What are the benefits of performing a SELECT query to check the available balance before executing an UPDATE query in the PHP banking system code?

Performing a SELECT query to check the available balance before executing an UPDATE query in the PHP banking system code helps to ensure that the account has sufficient funds to complete the transaction. This prevents overdrawing the account and helps maintain accurate account balances. By verifying the available balance before updating it, we can avoid potential errors and maintain the integrity of the banking system.

// Check available balance before updating
$account_number = 123456789; // Example account number
$amount_to_withdraw = 100; // Example amount to withdraw

// SELECT query to get current balance
$query = "SELECT balance FROM accounts WHERE account_number = $account_number";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$current_balance = $row['balance'];

if ($current_balance >= $amount_to_withdraw) {
    // UPDATE query to deduct the amount from the balance
    $new_balance = $current_balance - $amount_to_withdraw;
    $update_query = "UPDATE accounts SET balance = $new_balance WHERE account_number = $account_number";
    mysqli_query($connection, $update_query);
    echo "Withdrawal successful. New balance: $new_balance";
} else {
    echo "Insufficient funds. Withdrawal failed.";
}