Precision loss whilst inserting a double into MySQL through PDO

做~自己de王妃 提交于 2020-01-03 16:40:26

问题


I've run into this really annoying behavior and I want to know if I'm doing something wrong, or if this is intentional (and if so, why).

Whenever I have a variable in php (5.3) that is of type double and I want to insert it into the database (MYSQL 5.0) in a field that is of type double, the value always gets rounded down to 6 digits behind the point when I'm using PDO. So the below code:

$stmt = $pdo->prepare("UPDATE someTable SET someDouble = :somePHPDouble;");
$number = 0.11124379542256;
$stmt->bindValue(':somePHPDouble', $number);
$stmt->execute();

Results in 0.111244 inserted into the db. But when I cast the variable to a string(!) in the binding expression like:

$stmt->bindValue(':somePHPDouble', (string)$number);

it inserts it properly as 0.11124379542256.

What is happening here ? I'm clueless. MySQL datatype of someDouble really is a double, and when inserting it through mysql console it just works. And the variable in php really is a double, so it seems to me that something goes wrong inside PDO.

Thanks in advance, -CodePoet.


回答1:


It is neither intentional, nor are you doing something wrong. It seems to be a PHP bug.

According to this bug report, it has been fixed for PHP 5.2.11, but only recently for the 5.3 branch, so you might want to check your exact PHP version against the ones mentioned there.



来源:https://stackoverflow.com/questions/1738074/precision-loss-whilst-inserting-a-double-into-mysql-through-pdo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!