"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Resolve the \"Call to a member function prepare() on null\" Error in Database Connectivity?

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

Published on 2024-11-08
Browse:469

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.

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();
    }
}

?>

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3