I have a problem when comparing two PHP values. The first value is being passed as a parameter in the query string, while the second parameter is a result of an sql query.
The logic I need here is to compare both values, so that if the user has enough credit, his payment can be processed, but otherwise, an error message is shown.
This is my code:
public function storeNewTicket($userId, $amount, $validity) {
$currentBalance = $this->getBalance($userId);
$floatCurrentBalance = floatval($currentBalance);
$floatAmount = floatval($amount);
if ($floatCurrentBalance > $floatAmount) {
/*Proceed with the insert*/
}
else {
echo "You don't have enough credit to process this payment."
}
}
In a seperate function in the same file called getBalance(), I am getting the current balance of the user from a different table and returning it as an object. I am 100% sure that this is working. Here is the code:
public function getBalance($userId) {
$stmt = $this->conn->prepare("SELECT balance FROM userbank WHERE UserId = ?");
$stmt->bind_param("s", $userId);
if ($stmt->execute()) {
$bal = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $bal['balance'];
} else {
return NULL;
}
}
The code is always going through the else clause and echoing: You don't have enough credit to process this payment.;
Can someone please help me understand how to convert the variables to decimals or floats and compare them?
getBalanceis an object ( array? ) - yet you use$floatCurrentBalance=floatval($currentBalance)~ surely if it is an object/array then you would need to access the value contained within ?$currentBalanceis an array. You need to access the specific array key, something like$floatCurrentBalance=floatval($currentBalance['balance'])Or better yet havegetBalanceactually return a float and not just the database row as an array$balance = $stmt->get_result()->fetch_assoc()~ that will return an array not a single value. From the manual"mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row as an associative array"fetch_assoc()is your own method, on a userland class, and not the php built in method, then$currentBalancecertainly is an array, probably with a single element. Why notvar_dump($this->getBalance($userId))and check for yourself$currentBalance['balance']will access the float. I suggest you change it in thegetBalance()function thoughj:return $balance['balance'];For good measure, you can rename the variable used in that function:$row = $stmt->get_result()->fetch_assoc(); $stmt->close(); return $row['balance'];The code will function the same, but it wont be as confusing for future you when you come back to make changes