我正在努力处理一些 PHP 代码,这些代码将商品的价格插入到 MySQL 数据库中。正在插入价格,但它总是向下舍入。
例如,如果我插入一个数字 9.99,它会在数据库中四舍五入为 9.00。
我认为这是 PHP 代码的问题,因为我在 phpMyAdmin 中使用 sql 语句手动插入数据,但数据没有被舍入。
我使用 item_price DECIMAL(7,2) NOT NULL
创建列,因此它应该接受小数位。
我还使用 echo
检查从 html 表单到达 .php 文件的值是否正确,并且显示的是带小数点的值。
我正在这样定义 $total
变量:
// Is repeated across multiple functions
$price = test_input($_POST["price-2"]);
$total += $price
这是将信息插入数据库的代码部分:
echo $total; // Returns a decimal value (eg 9.99)
$sql = "INSERT INTO purchase_requests (submitted_by, request_type, summary,
cost_centre, location, location_details, transport, total_price, approved,
approver, paid) VALUES (?,'purchase',?,?,?,?,'false',?,'pending','pending','pending');";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL Error";
} else {
mysqli_stmt_bind_param($stmt, "issssi", $submitter, $summary, $costCentre,
$location, $locationDetails, $total);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
谁能理解为什么会发生这种情况?谢谢!
最佳答案
您要用这行代码告诉 PHP 将值保存为整数:
mysqli_stmt_bind_param($stmt, "issssi", $submitter, $summary, $costCentre, $location, $locationDetails, $total);
i
代表“整数”。如果你想插入 double 值,你必须使用 d
。
在您的情况下,您的行变为:
mysqli_stmt_bind_param($stmt, "issssd", $submitter, $summary, $costCentre, $location, $locationDetails, $total);
关于php - 为什么这个 PHP 函数/MySQL 数据库会向下舍入十进制值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57538224/