I have a PHP application that is supposed to insert an monetary value into a MariaDB whose table column was set to decimal (10,2)
To ensure the formatting is correct I initially did an echo statement to make sure the result using what I thought should be the correct formatting....
number_format($variable-to-be-converted, 2, '.', '');
However, when I assign that format conversion I get told (by the mysqli error code) that the decimal value is incorrect. I have tried adjusting the decimal placing between 13, 10, and 4; alas no joy.
Any ideas would be appreciated t-i-a
include '../includes/dbt.php';
//make sure a residence tile was selected or send them back to /play/index.php
if (!isset($_GET['residence'])) {
//code here
} else if (isset($_COOKIE['startingBal'])){
session_start();
setCookie("residence", $_GET['residence'], time() + 86400);
$residence = $_COOKIE['residence'];
$balance = $_COOKIE['startingBal'];
$newBal = '';
switch ($residence) {
case 'option1':
$newBal = $balance - 3200;
break;
case 'option2':
$newBal = $balance - 3000;
break;
case 'option3':
$newBal = $balance - 800;
break;
case 'option4':
$newBal = $balance - 700;
break;
default:
$balance;
}
$formattedNewBal = number_format($newBal, '2','.','');
$ingameStatsUpdate = "INSERT INTO ingameStats (`nickname`, `residence`, `newBal`) VALUES ('$nickname', '$residence', '$formattedNewBal')";
if (mysqli_query($conn, $ingameStatsUpdate)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
//unset starting balance cookie since now the database will keep track of the balance moving forward
setCookie("startingBal", "", time() -3600);
// close connection
mysqli_close($conn);
}
There's two problems.
First, you're not setting $residence
correctly. Calling setcookie()
doesn't update the $_COOKIE
array, so $residence = $_COOKIE['residence'];
won't set it to the value you just assigned. See Why are my cookies not setting?
Second, your default:
case doesn't set $newBal
. So if none of the cases match, $newBal
still has an empty string, which is an invalid floating point value in MySQL.
session_start();
$residence = $_GET['residence'];
setCookie("residence", $residence, time() + 86400);
$balance = $_COOKIE['startingBal'];
switch ($residence) {
case 'option1':
$newBal = $balance - 3200;
break;
case 'option2':
$newBal = $balance - 3000;
break;
case 'option3':
$newBal = $balance - 800;
break;
case 'option4':
$newBal = $balance - 700;
break;
default:
$newBal = $balance;
}