Home > Enterprise >  How to fetch balance and compare with input?
How to fetch balance and compare with input?

Time:11-28

I want to compare user balance from database and the input amount. if user balance is below (int) 10 in the database. and the form input is (int) 12.

In the below code, I want the sender to see "insufficient balance" if he did not have enough balance inputted in the form;

public function makeTransactions($from, $amount, $to) {
    try {
        $check = $this->db->prepare("SELECT balance FROM `Users` WHERE `email` = '$from' "); 
        $check->execute();
        $available = $check->fetch(PDO::FETCH_ASSOC);

        if ($available < $amount) {
            $msg = "Insufficient balance!";
            return $msg;
        } else {
            $sendNow = $this->db->prepare("UPDATE `Users` SET balance = balance-'$amount' WHERE `email` = '$from' ");
            $proceed = $sendNow->execute(); 

            if ($proceed) {
                $proceed = $this->db->prepare("UPDATE `Users` SET balance = balance '$amount' WHERE `email` = '$to' ");
                $result = $proceed->execute(); 

                if ($result) {
                    $msg = "Transaction successful";
                    return $msg;
                } else {
                    $msg = "Transaction failed";
                    return $msg;
                }
            }
        }
    }
}

CodePudding user response:

Try to use $check->fetchColumn()

https://www.php.net/manual/en/pdostatement.fetchcolumn.php

  • Related