问题描述
说实话,这是一个非常简单的问题.我一直在谷歌上寻找解决方案,但似乎没有任何效果.我的数据库中有以下字段:
It's a pretty simple question to be honest. I've been looking for a while now on Google for a solution but nothing seems to work. I have the following field in my database:
decimal(2,1)
我在 PHP 中有两个变量(来自通过 POST 插入表单的值)我想将它们加在一起,然后插入到这个字段中.
I have two variables in PHP (which come from values inserted into a form via POST) I want to add together and then insert into this field.
$sql2 = $link->prepare("INSERT INTO league_stats (match_id, rating)
VALUES (?, ?)");
$sql->bind_param("ii", $match_id, $rating);
$match_id = $_SESSION["match_id"];
$rtg1 = $_POST[$rating_1"];
$rtg2 = $_POST[$rating_2"] / 10;
$rating = $rtg1 + $rtg2;
例如,rtg1 为 7,rtg2 为 3 除以 10,因此结果为 0.3.然后我将这两个数字相加得到 7.3.当我将它插入数据库时,它总是显示第二个数字为 0.所以它会显示为 7.0 而不是 7.3.我尝试了许多不同的方法,但总是得到完全相同的结果.
For example, rtg1 would be 7 and rtg2 would be 3 divided by 10 so it comes out as 0.3. I then add these two numbers together to make 7.3. When I go to insert it into the database, it always displays the second digit as 0. So instead of 7.3 it would come out as 7.0. I've tried many different methods but I always get the exact same result.
我什至将 $rating 分配给一个原始值,只是为了测试我的变量是否有问题:
I even assigned $rating to a raw value just to test if there was something wrong with my variables:
$rating = 7.5
仍然是 7.0.
有人可以提供一个示例,说明如何将浮点类型的 PHP 变量正确插入 MySQL 吗?还可以解释如何正确地将两个浮点值加在一起?谢谢!
Could somebody please provide an example of how to correctly insert a float type PHP variable into MySQL? And also maybe explain how to correctly add two float values together? Thanks!
推荐答案
你告诉 php 将 $match_id
和 $rating
转换为整数.你应该使用:
You are telling php to cast $match_id
and $rating
to integer. You should use:
$sql->bind_param("id", $match_id, $rating);
而不是
$sql->bind_param("ii", ...
这篇关于将 PHP 浮点数/十进制值插入 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!