【问题标题】:Why PHP PDO bindValue not binding?为什么 PHP PDO bindValue 不绑定?
【发布时间】:2014-06-12 11:31:07
【问题描述】:

我有一个查询我的数据库的函数:

public function query($sql, $params = array()) {
    // reset error back to false
    $this->_error = false;

    // check query to prepare
    if($this->_query = $this->_pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
            print_r($this->_pdo->errorInfo());
        }
        // check query execution
        if ($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            // error
            $this->_error = true;
        }
    }

    return $this;
}

但是有些东西不起作用。 $this->_query->bindValue($x, $param); 行没有做它应该做的事情。没有发生绑定。将参数放入函数的数组似乎很好。 $sql 语句也很好并且正在返回:

INSERT INTO responders (`username`, `password`, `salt`) VALUES (?, ?, ?)

这对于使用 bind 方法应该是完美的。但是经过 foreach 循环之后,什么都没有改变,_query var 仍然是一样的。所以根本不会进入数据库。我也树使用errorInfo并返回:

Array ( [0] => 00000 [1] => [2] => ) 

谁能告诉我我在这里缺少什么?

【问题讨论】:

  • 您是否费心检查 bindValue() 调用的返回值?
  • @TheFrost:这有什么好处?您会将其更改为相等测试,并且准备好的语句将丢失。例如你主张进一步破坏剧本。
  • 有趣.. bindValue()调用的返回值为:1
  • 在运行查询之前查询错误信息似乎为时过早。 after 执行后会带来什么? debugDumpParams 可能会提供更多见解。
  • 我可以问一下为什么我的问题获得了反对票吗?

标签: php pdo bindvalue


【解决方案1】:

不用看那些乱七八糟的代码,这就是这个函数的样子

public function query($sql, $params = array()) {
    $query = $this->_pdo->prepare($sql);
    $query->execute($params);
    return $query;
}

别忘了set PDO in exceptions mode

【讨论】:

  • 嗯...我敢肯定,我不是最伟大的 PHP 编码器。但至少要有礼貌。如果你是想进步的人,问问题没有错……
猜你喜欢
  • 2013-03-08
  • 2015-06-10
  • 2013-01-03
  • 2011-02-11
  • 2014-01-26
  • 2016-10-12
  • 2013-11-12
  • 2012-07-31
相关资源
最近更新 更多