【问题标题】:Call to a member function fetchAll() on a non-object [duplicate]在非对象上调用成员函数 fetchAll() [重复]
【发布时间】:2014-06-05 20:29:01
【问题描述】:

我不知道为什么它会返回Call to a member function fetchAll() on a non-object 错误,因为我在 _sth 对象上使用了 fetchAll 方法。

有人知道为什么会这样吗?

FormValidator PHP

$users = $this->_db->query("SELECT * FROM $ruleValue WHERE $input = ?", array($inputValue));
if($users->count()) {
    $this->addError($input, $rule);
}

方法

public function query($sql, $params = array()) {
    $this->_sth = $this->_dbh->prepare($sql);

    if($this->_sth = $this->_sth->execute($params)) {
        return $this->_sth->fetchAll(PDO::FETCH_OBJ);
    }

    return false;
}

【问题讨论】:

  • 我在函数上使用它的唯一原因是我不必一遍又一遍地重复相同的代码。
  • execute() 返回一个布尔值。它没有fetchAll() 函数。只需if($this->_sth->execute($params)) {。
  • 没有太多可重复的代码,但安全性存在巨大漏洞。您应该删除查询中的所有变量
  • WHERE $input 这里例如

标签: php mysql oop object pdo


【解决方案1】:
if($this->_sth = $this->_sth->execute($params)) {

单个= 是一个赋值运算符。 execute() 返回布尔值 TRUE 或 FALSE,您将其分配给 $this->_sth。

    return $this->_sth->fetchAll(PDO::FETCH_OBJ);

TRUE 和 FALSE 都不是对象,并且没有 fetchAll() 方法。

@RocketHazmat 的评论是正确的,您可以测试execute() 的返回值 将其分配给_sth。示例:

if($this->_sth->execute($params)) {
    return $this->_sth->fetchAll(PDO::FETCH_OBJ);
}

【讨论】:

    【解决方案2】:

    正如我已经说过的,有两个巨大的缺陷。

    1. 不要在你的类中引入状态。使用局部变量并返回结果。
    2. 永远不应查询中没有单个变量。

    不要在

    中引入状态
    public function query($sql, $params = array()) {
        $sth = $this->_dbh->prepare($sql);
        $sth->execute($params);
        return $sth->fetchAll(PDO::FETCH_OBJ);
    }
    

    就是你所需要的。

    别偷懒,写完整的查询。

    $user = $this->_db->query("SELECT * FROM users WHERE param = ?", [$inputValue]);
    if($user) {
        $this->addError($input, $rule);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-28
      • 2015-05-13
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      • 1970-01-01
      相关资源
      最近更新 更多