Reputation:
i try to write my own PDO wrapper-class, my statements always return true
and I can't fetch anything.
Here is my DB
class
class DB {
private $db;
private $host = "localhost";
private $database = "test";
private $user = "test";
private $password ="test";
public function __construct(){
try {
$this->db = new \PDO("mysql:host=" . $this->host . ";dbname=" . $this->database, $this->user, $this->password);
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $error) {
die("Verbindung zur Datenbank fehlgeschlagen: <br>" . $error);
}
}
public function run($sql, $args = []){
try{
$stmt = $this->db->prepare($sql);
$result = $stmt->execute($args);
return $result;
} catch(\PDOException $error) {
die("Fehler bei Datenbankabfrage: <br>". $error);
}
}
}
And here I instantiate a new instance of my class and try to fetch data
$DB = new DB();
$data = $DB->run("SELECT * FROM testtbl")->fetchAll();
Without the fetchAll()
it returns true and with it throws an error in my error.log
PHP Fatal error: Uncaught Error: Call to a member function fetchAll() on boolean
It would be nice if someone can help me.
Upvotes: 0
Views: 1145
Reputation: 147206
PDOStatement::execute
just returns a boolean which says whether the query succeeded or not. You need to call fetchAll
on the statement, so instead of
return $result;
you should have
return $stmt;
Upvotes: 1