将PHP浮点/小数值插入到MySQL中 [英] Inserting PHP float/decimal values into MySQL

查看:147
本文介绍了将PHP浮点/小数值插入到MySQL中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说实话,这是一个非常简单的问题。我一直在Google上寻找一个解决方案,但似乎没有任何工作。

 十进制(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆