What data type should be used to store user balances in a database to ensure accurate calculations in PHP?

To ensure accurate calculations in PHP when storing user balances in a database, it is recommended to use a decimal data type with a specific precision and scale. This data type is suitable for storing monetary values as it can handle decimal numbers without rounding errors. By using the decimal data type, you can maintain the precision of user balances and avoid unexpected results in calculations.

// Create a table in the database with a decimal data type for storing user balances
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "CREATE TABLE user_balances (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    balance DECIMAL(10, 2) NOT NULL
)";

if ($conn->query($sql) === TRUE) {
    echo "Table user_balances created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}

$conn->close();