What are the best practices for updating a user's balance in a PHP application?

When updating a user's balance in a PHP application, it is important to ensure that the update is done securely and accurately to prevent any potential issues with the user's account balance. One of the best practices is to use a database transaction to ensure that the balance update is atomic and consistent.

<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Begin a transaction
$pdo->beginTransaction();

try {
    // Retrieve the user's current balance
    $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = :user_id");
    $stmt->execute(['user_id' => $user_id]);
    $current_balance = $stmt->fetchColumn();

    // Update the user's balance
    $new_balance = $current_balance + $amount;
    $stmt = $pdo->prepare("UPDATE users SET balance = :new_balance WHERE id = :user_id");
    $stmt->execute(['new_balance' => $new_balance, 'user_id' => $user_id]);

    // Commit the transaction
    $pdo->commit();
    
    echo "Balance updated successfully!";
} catch (Exception $e) {
    // Rollback the transaction if an error occurs
    $pdo->rollBack();
    
    echo "Error updating balance: " . $e->getMessage();
}