0

index.php:

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

and get the error :

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

If I running in the sql() method, execute() and fetch() the data inside it , it can truly get the data , but put the execute() and fetch() to the query() method, getting the error message, Any Idea? ;

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Fan
  • 1,124
  • 3
  • 17
  • 35
  • 1
    `false` means that your query failed, use http://php.net/manual/en/pdostatement.errorinfo.php to see the error. – u_mulder Dec 18 '16 at 08:10
  • @u_mulder I var_dump(statement) and got ture ./Applications/MAMP/htdocs/Test/Program/Component/Db.php:60:boolean true – Fan Dec 18 '16 at 08:15
  • Use the function in my comment, __please__ – u_mulder Dec 18 '16 at 08:17
  • /Applications/MAMP/htdocs/Test/Program/Component/Db.php:61: array (size=3) 0 => string '00000' (length=5) 1 => null 2 => null – Fan Dec 18 '16 at 08:25

3 Answers3

2

There is an error in your code. In this line:

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

The execute() method is PDOStatement::execute. This is the signature:

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

Which means it returns boolean. Your mistake is you are trying to call fetchAll() on a boolean.

For more information about the error message, see this page.

Community
  • 1
  • 1
Rei
  • 6,263
  • 14
  • 28
0

Try this

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

And

$data = $db->query('select * from test where name = :name',$param);
ashkufaraz
  • 5,179
  • 6
  • 51
  • 82
0
$statement = $this->statement->execute(); 

Your code is returning a bool value. But your statement object is cotaining your processed data. By the way you have to get returned values from main statement via:

 $this->statement->fetchAll();

Regards.

mfkocak
  • 87
  • 4