【问题标题】:Uncaught Error: Call to a member function fetchAll() on boolean未捕获的错误:在布尔值上调用成员函数 fetchAll()
【发布时间】:2017-05-03 13:11:44
【问题描述】:

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 

数据库.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()方法中,得到错误信息,有什么想法吗? ;

【问题讨论】:

  • false 表示您的查询失败,使用php.net/manual/en/pdostatement.errorinfo.php 查看错误。
  • @u_mulder 我 var_dump(statement) 并得到了 ture ./Applications/MAMP/htdocs/Test/Program/Component/Db.php:60:boolean true
  • 使用我评论中的功能,
  • /Applications/MAMP/htdocs/Test/Program/Component/Db.php:61: array (size=3) 0 => string '00000' (length=5) 1 => null 2 => 空

标签: php pdo execute


【解决方案1】:

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

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

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

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

这意味着它返回布尔值。 您的错误是您尝试在布尔值上调用 fetchAll()

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

【讨论】:

    【解决方案2】:

    试试这个

     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);
    

    【讨论】:

    • 这个案子很好,但我还是不明白我做错了什么。
    • 最好返回一个语句。让您的功能更加灵活和有用
    【解决方案3】:
    $statement = $this->statement->execute(); 
    

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

     $this->statement->fetchAll();
    

    问候。

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 2017-06-07
      • 2020-07-29
      • 2019-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多