Null Member Function Error: A Problem in Database Connectivity
When encountering a "Call to a member function prepare() on null" error, the issue usually stems from an uninitialized variable within the class instance. In your case, the problem lies in the missing initialization of the $pdo variable.
Within your Category class, the fetch_all() and fetch_data() methods both require a PDO connection. However, the code provided does not establish this connection explicitly. To resolve this error, you need to ensure that the $pdo variable is initialized within the global scope before calling the class methods.
<code class="php"><?php // Instantiate a new PDO object globally $pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass); class Category { public function fetch_all() { global $pdo; // Use the initialized $pdo variable to prepare the SQL query $query = $pdo->prepare("SELECT * FROM dd_cat"); $query->execute(); return $query->fetchAll(); } public function fetch_data($cat_id) { global $pdo; // Use the initialized $pdo variable to prepare the SQL query $query = $pdo->prepare("SELECT * FROM dd_cat WHERE cat_id = ?"); $query->bindValue(1, $cat_id); $query->execute(); return $query->fetch(); } } ?></code>
By initializing the $pdo variable globally and ensuring it is used within the class methods, you will establish a proper database connection and resolve the "Call to a member function prepare() on null" error.
The above is the detailed content of How to Resolve the \'Call to a member function prepare() on null\' Error in Database Connectivity?. For more information, please follow other related articles on the PHP Chinese website!