How to Resolve the \'Call to a member function prepare() on null\' Error in Database Connectivity?

Linda Hamilton
Release: 2024-11-01 13:44:29
Original
839 people have browsed it

How to Resolve the

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!