2012-08-28 64 views
2

我有这个奇怪的问题。为什么这两个实现返回不同的结果?PDO:绑定参数和连接字符串之间的区别

$db = DbBase::getInstance(); 
    $stmt = $db->prepare('SELECT round(round(9.50 * :amount, 2) * 23 * 0.01, 2)'); 
    $stmt->execute(array(':amount' => 1)); 
    echo $stmt->fetchColumn(); 

    Result: 2.18 

    $db = DbBase::getInstance(); 
    $stmt = $db->prepare('SELECT round(round(9.50 * 1, 2) * 23 * 0.01, 2)'); 
    $stmt->execute(); 
    echo $stmt->fetchColumn(); 

    Result: 2.19 

当我绑定量它给了我不同的结果。由于SQL注入,我宁愿不连接字符串。

+0

什么是 “落后” $ DB?一个sqlite,MySQL,postgresql,???连接? – VolkerK

+0

MySQL,它是PDO的包装。 – PPPHP

回答

4

当使用阵列来传递数据,该数据被作为字符串传递:

docs

值的数组与尽可能多的元件,因为在结合的参数正在执行的SQL语句。所有值都被视为PDO :: PARAM_STR。

但是,当您手动输入1直接将查询作为int处理时。让我看看是否可以进一步挖掘一下,看看当一个字符串被转换为一个int时,内部发生了什么。

编辑:这可能是已经提交并接受most similar bugs之一:

1) 
SET @a = 1; 
SELECT @a; 

2) 
SET @a = 1.1; 
SELECT @a; 

.. and this 

3) 
SET @a = 1.1; 
SELECT @a + 7; 
returns '8.100000000000000000000000000000' 
(probably the addition will convert "1.1" to a double, the result 
of the addition is also a DOUBLE and finally the DOUBLE is converted 
to a string - that should be OK as well as far as I can understand) 

所以看起来在内部,当你把它传递一个int MySQL是转换为双。这将很好地解释你所看到的行为。

这是其他同类(数字并不完全正确)的列表错误你可能感兴趣的:

http://bugs.mysql.com/bug.php?id=46037

http://bugs.mysql.com/bug.php?id=35071

http://bugs.mysql.com/bug.php?id=35071 < - 好一个展示Win和林之间的差异

filtered list of data type bugs我仔细阅读了哪些有趣的阅读。

编辑2:啊!

这里是一个bug that rather perfectly说明您的问题:

Reproduce code: 
--------------- 
CREATE TABLE my_db.my_table (
    id int(10) unsigned NOT NULL auto_increment, 
    PRIMARY KEY (id) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

<?php 
$DB = new PDO('mysql:dbname=my_db;host=localhost', 'user', 'pass'); 
$stmt = $DB->prepare('select * from my_table where id>?'); 
$stmt->bindValue(1, 13); 
$stmt->execute(); 
?> 

or 

<?php 
$DB = new PDO('mysql:dbname=my_db;host=localhost', 'user', 'pass'); 
$stmt = $DB->prepare('select * from my_table where id>?'); 
$stmt->execute(array(13)); 
?> 

Expected result: 
---------------- 
select * from my_table where id>13 

Actual result: 
-------------- 
select * from my_table where id>'13' 
+0

对于“让我看看我是否可以进一步挖掘以查看当字符串被转换为int为内部时发生了什么”。等待:) – swapnesh

+1

@swapnesh是的,我很想知道事情如何在这些宝石的内部工作:) – Fluffeh

+0

嗯,我必须纠正我的问题。其实我想绑定浮点值,我无法找到一个方法来做到这一点。 – PPPHP

相关问题