Reputation: 39
I'm getting this error ('Uncaught Error: Call to a member function prepare() on null') when passing a pdo instance into a class method. The error is thrown by the selectAll method. Stack trace is #0. I can't work out why I'm getting this error.
class QueryBuilder {
protected $pdo;
protected $newTask;
public function __construct($pdo) {
$this->pdo = $pdo;
}
//Selects from table and returns to view
public function selectAll($table, $intoClass) {
$stmt = $this->pdo->prepare("select * from {$table} limit 1, 9");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_CLASS, $intoClass);
}
//Adds a new task to the table
public function addToTable($table, $newTask) {
$done = 0;
try {
$stmt = $this->pdo->prepare("insert into {$table} (description, completed) values (:todo, :done)");
$stmt->bindParam(':todo', $newTask);
$stmt->bindParam(':done', $done);
$stmt->execute();
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
This is the index.php file, where I've saved the pdo variable.
error_reporting(E_ALL);
ini_set('display_errors', '1');
require "Task.php";
require "config.php";
require "connection.php";
require "QueryBuilder.php";
$pdo = Connection::make();
$query = new QueryBuilder($pdo);
$tasks = $query->selectAll('todos', 'Task');
$newTask = $_POST['todo'];
require 'user.view.php';
Connection.php is where I initialize pdo.
class Connection {
public static function make() {
try {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', '
', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
die ($e->getMessage());
}
}
}
Upvotes: 0
Views: 66
Reputation: 218960
The connection you're creating is the return value of the static function you're calling:
$pdo = Connection::make();
But that function doesn't return anything, making that connection object null
:
public static function make() {
try {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', ' ', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
die ($e->getMessage());
}
}
Return the connection object from the function:
public static function make() {
try {
return new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', ' ', array(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
die ($e->getMessage());
}
}
Upvotes: 2