Home >Backend Development >PHP Tutorial >Why am I getting a \'Fatal error: Call to a member function prepare() on null\' when trying to retrieve categories?
Fatal Error: Mysterious Call to a Null Member Function
Query:
I'm encountering the puzzling error "Fatal error: Call to a member function prepare() on null" when trying to retrieve a list of categories using this code:
<code class="php">$category = new Category; $categories = $category->fetch_all();</code>
Context:
The Category class has the following methods:
<code class="php">class Category { public function fetch_all() { global $pdo; $query = $pdo->prepare("SELECT * FROM dd_cat"); ... } public function fetch_data($cat_id) { global $pdo; $query = $pdo->prepare("SELECT * FROM dd_cat WHERE cat_id = ?"); ... } }</code>
I've used this code successfully in two other sections of my project, but it's giving me trouble here.
Response:
The issue arises because the $pdo variable is null. It must be initialized with a PDO object before the class methods can be called. This is due to the way the methods have been implemented in the Category class.
To fix the error, add the following code to your script:
<code class="php">$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);</code>
Ensure that this code is placed in the global scope, before any calls to the Category class methods.
The above is the detailed content of Why am I getting a \'Fatal error: Call to a member function prepare() on null\' when trying to retrieve categories?. For more information, please follow other related articles on the PHP Chinese website!