Reputation: 1180
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? ;
Upvotes: 0
Views: 3105
Reputation: 85
$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.
Upvotes: 0
Reputation: 6363
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.
Upvotes: 2
Reputation: 5297
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);
Upvotes: 0