0

I do not know why it returns the Call to a member function fetchAll() on a non-object error because I am using the fetchAll method on the _sth object.

Does anybody know why it does this?

FormValidator PHP

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

Method

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;
}
Kid Diamond
  • 2,232
  • 8
  • 37
  • 79

2 Answers2

3
if($this->_sth = $this->_sth->execute($params)) {

The single = is an assignment operator. execute() returns a boolean TRUE or FALSE, and you're assigning that to $this->_sth.

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

Neither TRUE nor FALSE is an object, and has no fetchAll() method.

The comment from @RocketHazmat is correct, you can test the return value of execute() without assigning it to _sth. Example:

if($this->_sth->execute($params)) {
    return $this->_sth->fetchAll(PDO::FETCH_OBJ);
}
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
1

As I said already, there are two HUGE flaws.

  1. DO NOT introduce state in your class. Use local variables and return the result.
  2. Ther should be not a single variable in the query ever.

DO NOT introduce state in

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

is ALL you need.

Don't be lazy, write full query.

$user = $this->_db->query("SELECT * FROM users WHERE param = ?", [$inputValue]);
if($user) {
    $this->addError($input, $rule);
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345