【问题标题】:Trouble to understand PDO bindValue and execute无法理解 PDO bindValue 并执行
【发布时间】:2016-06-09 05:52:13
【问题描述】:

最近开始学习PDO,搞不懂bindValue的行为,直接用数组执行。

$statement = $db->prepare('SELECT * FROM category WHERE `category_name`=?');
$statement->bindValue(1, 'Swimwear'); // It's okey
$statement->execute();

//direct execute with array
$statement->execute(array('Swimwear')); // It's also okey

但真正的问题是为什么我不必使用 like?

$statement->execute(array(1 => 'Swimwear')); // It's not okey, Not working

【问题讨论】:

    标签: php mysql pdo


    【解决方案1】:

    $statement->execute(array(1 => 'Swimwear')); 不起作用,因为该值应该在索引 0 中,而不是 1。使用此语法时,正确的代码是:

    $statement->execute(array(0 => 'Swimwear'));
    

    虽然我认为在array('Swimwear') 上使用如此复杂的语法没有任何意义。

    【讨论】:

    • 你是对的,但我不知道 BindValue 从 1 开始索引的差异,我现在关于从 0 开始的数组。
    • 很高兴看到您再次像往常一样给出正确答案。
    【解决方案2】:

    使用 PDO,您可以通过三种方式添加占位符值。

    您可以使用bindValue 单独添加它们。

    您可以将它们添加到一个简单的数组中。

    您可以使用关联数组添加它们如果您已命名它们。

    因此,要使该样式生效,您需要为准备好的语句以及传递给execute 的数组添加一个名称:

    $statement = $db->prepare('SELECT * FROM category WHERE `category_name`=:category');
    $statement->execute(array(':category' => 'Swimwear'));
    

    没有名为 1 的占位符,所以这不起作用。

    bindValue() 函数采用 1 索引值,这就是 bindValue(1, 'Swimwear') 调用起作用的原因。这是通常的 0 索引编程规则的一个例外。

    要使其与关联样式一起使用,您需要这样称呼它:

    $statement->execute(array(0 => 'Swimwear'));
    

    【讨论】:

    • 我使用的是 category_name=? 而不是指定的。
    • 那些是未命名的,所以你应该使用简单的数组样式来填充它们。我发现命名占位符更难弄乱,你不会错误地颠倒某些值的顺序,如果你有十几个列要填充,这很容易做到。
    • 但是 BindValue 与未命名的类似:$statement->bindValue(1, 'Swimwear');
    • 当使用 category_name=? 时,它期望从索引 0 中找到元素,而不是 1。
    • @RivnatNasah 与往常一样,请阅读the documentation on bindValue,它声明它是 1-indexed。常规数组不是。这只是 PDO 的怪癖之一。
    猜你喜欢
    • 2018-06-15
    • 2011-04-13
    • 2012-09-05
    • 2014-07-28
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 2015-05-12
    • 2014-01-23
    相关资源
    最近更新 更多