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? ;
Advertisement
Answer
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.