Fatal error: Call to a member function prepare() on null
The PHP error Fatal error: Call to a member function prepare() on null is one of those frustrating runtime exceptions that halts execution immediately. It occurs when your code attempts to invoke the prepare() method on a variable that evaluates to null. In practical terms, this means you are trying to run a SQL query against a database connection object that hasn't been instantiated yet, has already been destroyed, or never existed in the first place.
While the error message points directly at a missing method call, it rarely tells you why the object is null. The root cause is almost always a scope issue: relying on global variables to pass state across file boundaries without explicit dependency injection.
The Global Variable Trap
In the scenario provided, the Category class relies on the global $pdo variable within its methods.
class Category {
public function fetch_all() {
global $pdo; // This accesses a variable from the outer scope
$query = $pdo->prepare("SELECT * FROM dd_cat");
// ...
}
}
This pattern works perfectly fine if $pdo is defined in the global namespace of the script where Category is instantiated. However, PHP file inclusion logic can be treacherous. Look closely at how the application loads its components:
require_once('includes/config.php');
require_once('includes/header.php');
include_once('includes/category.php'); // Loads the class definition
// ... HTML and partials ...
$category = new Category;
$categories = $category->fetch_all();
The critical detail lies in the execution order. config.php likely initializes $pdo. Then, header.php is included. If header.php contains any code that initializes a user session or loads additional global state (like a custom $user object referenced later), it might inadvertently reset the global namespace or, more subtly, if category.php is included before config.php defines $pdo, you have a problem.
However, a more common culprit in these specific architectures is that header.php or another included file modifies the global variables array, or the variable $pdo is defined inside a function scope within config.php and not exported to the global scope correctly. But often, the real issue is simpler: variable shadowing.
If you look at the code block using global $pdo, you are accessing the top-level $pdo. If another part of your application (perhaps inside header.php) defines a local variable named $pdo or if the config.php file sets up an environment where $pdo is not globally accessible in the way expected, the global keyword will grab that wrong scope.
Wait, there is a more specific red flag in the provided code structure. The line require_once('includes/category.php') happens before the instantiation of the class in the main script. This is fine for loading the definition. But consider the state of $pdo at the exact moment fetch_all() is called.
If config.php successfully creates $pdo, why does it fail? The answer often lies in how the variable is accessed. Using global $pdo inside a class method couples that class tightly to the global state. If header.php includes something that initializes a local $pdo (perhaps for testing or debugging), and then the main script runs, you might think you are accessing the database connection but actually be accessing a null value if the initialization failed silently earlier in the chain.
Refactoring for Stability
The most robust solution is to remove the reliance on the global keyword entirely. Instead of guessing where $pdo lives, pass it explicitly into the class. This decouples your logic from the global namespace and makes the flow of data deterministic.
Here is how you should structure the Category class:
class Category {
private $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
}
public function fetch_all() {
$query = $this->pdo->prepare("SELECT * FROM dd_cat");
$query->execute();
return $query->fetchAll();
}
public function fetch_data($cat_id) {
$query = $this->pdo->prepare("SELECT * FROM dd_cat WHERE cat_id = ?");
$query->bindValue(1, $cat_id);
$query->execute();
return $query->fetch();
}
}
Then, in your main script (e.g., index.php or the file containing the menu logic), you must instantiate the class with the database connection:
require_once('includes/config.php'); // Ensures $pdo is loaded here
require_once('includes/category.php'); // Loads the updated class definition
$category = new Category($pdo); // Pass $pdo explicitly
$categories = $category->fetch_all();
This approach eliminates ambiguity. You are no longer asking PHP, "Where is $pdo?"; you are telling it exactly which database connection to use. It also makes testing significantly easier, as you can mock the PDO object without touching global variables.
Why This Matters
The shift from global $pdo to dependency injection (passing $pdo to the constructor) is a standard best practice for a reason. It prevents silent failures where a variable exists in one scope but not another, or where a variable name clashes with a local definition in an included file. The "same code works elsewhere" phenomenon usually happens because the global state of those other files is differentâperhaps they didn't include a file that shadowed the variable, or they ran the script in a different order.
By making dependencies explicit, you ensure that your class requires exactly what it needs to function, regardless of how many times header.php or footer.php are loaded during the request lifecycle.