我不知道为什么它会返回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;
}
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);
}
正如我已经说过的,有两个巨大的缺陷。
- 不要在课堂上介绍州。使用局部变量并返回结果
- 查询中应该有而不是单个变量
请勿在中引入状态
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);
}