将PHP浮点/小数值插入到MySQL中 [英] Inserting PHP float/decimal values into MySQL
问题描述
十进制(2,1)
在数据库中有以下字段:
我在PHP中有两个变量(来自通过POST插入到表单中的值)我想将它们加在一起,然后插入到这个字段中。 p>
$ 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.3,它会以 7.0 出现。我已经尝试了许多不同的方法,但我总是得到完全相同的结果。
我甚至将$评级分配到一个原始值,只是为了测试是否有什么问题变量:
$ rating = 7.5
仍然以7.0的形式出现。
有人可以提供一个如何正确地将一个float类型的PHP变量插入MySQL的例子吗?也可以解释如何正确添加两个浮点值在一起?谢谢!
你正在告诉php来输入 $ match_id
code> $ rating 为整数。您应该使用:
$ sql-> bind_param(id,$ match_id,$ rating);
而不是
$ sql-> bind_param(ii,...
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)
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;
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.
I even assigned $rating to a raw value just to test if there was something wrong with my variables:
$rating = 7.5
Still comes out as 7.0.
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!
You are telling php to cast $match_id
and $rating
to integer. You should use:
$sql->bind_param("id", $match_id, $rating);
instead of
$sql->bind_param("ii", ...
这篇关于将PHP浮点/小数值插入到MySQL中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!