Uncaught Error: Call to a member function fetchAll() on boolean

Uncaught Error: Call to a member function fetchAll() on boolean

index.php:

$db = new Db();
$param = [':name' => 'Alex'];
$data = $db->sql('select * from test where name = :name',$param)->query();
var_dump($data);

并得到错误:

 Fatal error: Uncaught Error: Call to a member function fetchAll() on boolean 

Db.php

   public function sql($sql,array $params = null)
    {   
        $sql = $this->connection->prepare($sql);

        if($params){
            foreach ($params as $key => $param) {
                $sql->bindParam($key, $param);
            }
        }

        $this->statement = $sql;
        return $this; 
    }


    public function query($type = 1)
    {
      $statement = $this->statement->execute();

      return ($type == 1) ? $statement->fetchAll(static::$DB_FETCH) : $statement->fetch(static::$DB_FETCH);
    }

如果我运行在sql()方法中,execute()和fetch()里面的数据,是可以真正拿到数据的,但是把execute()和fetch () 到 query() 方法,得到错误信息,有什么想法吗? ;

试试这个

 public function query($sql,array $params = null,$type = 1)
    {
      $sql = $this->connection->prepare($sql);

      if($params){
          foreach ($params as $key => $param) {
              $sql->bindParam($key, $param);
          }
      }

      $this->statement = $sql;

      $statement = $this->statement->execute();

      return ($type == 1) ? $statement->fetchAll(static::$DB_FETCH) : $statement->fetch(static::$DB_FETCH);
    }

$data = $db->query('select * from test where name = :name',$param);

您的代码有错误。 在这一行中:

$statement = $this->statement->execute();

execute()方法是PDOStatement::execute。 这是签名:

public bool PDOStatement::execute ([ array $input_parameters ] )

这意味着它 returns 布尔值。 你的错误是你试图在布尔值上调用 fetchAll()

有关错误消息的详细信息,请参阅 this page

$statement = $this->statement->execute(); 

您的代码正在返回一个布尔值。但是您的语句对象包含您处理过的数据。顺便说一下,您必须通过以下方式从主语句获取返回值:

 $this->statement->fetchAll();

此致。