How can MySQL's FLOAT and DOUBLE data types be used to store currency values in PHP?
When storing currency values in MySQL using FLOAT and DOUBLE data types, precision can be lost due to the way floating-point numbers are stored. To accurately store currency values, it is recommended to use DECIMAL data type with a specified precision and scale. This will ensure that the values are stored accurately without any loss of precision.
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Define currency value
$currencyValue = 10.50;
// Insert currency value into MySQL using DECIMAL data type
$sql = "INSERT INTO currency_table (value) VALUES ('$currencyValue')";
$conn->query($sql);
// Retrieve currency value from MySQL
$sql = "SELECT value FROM currency_table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$currencyValue = $row["value"];
echo "Currency value: " . $currencyValue;
}
} else {
echo "0 results";
}
// Close MySQL connection
$conn->close();
Keywords
Related Questions
- What are the advantages of using a SQL database over a text file for storing data in a PHP script?
- What are the differences in handling input values between simple text fields and more complex elements like checkboxes, radio buttons, and text areas in PHP?
- How can the PHP code be modified to prevent SQL from changing the IDs randomly during updates?