Home > Database > Mysql Tutorial > body text

Why am I getting the error \'Fatal error: Call to a member function query() on null\'?

Mary-Kate Olsen
Release: 2024-10-28 12:32:02
Original
684 people have browsed it

Why am I getting the error

"Fatal error: Call to a member function query() on null" Explained

This error arises when trying to access the query() method of a null variable. Typically, this occurs when attempting to execute database queries without establishing a database connection or when the $db variable hasn't been properly initialized.

Diagnosis:

In the provided code, the error seems to originate from line 7:

<code class="php">$result = $db->query("SELECT COUNT(UserId) FROM users WHERE UserName = '$username'");</code>
Copy after login

However, line 3 of the code initializes the $db variable:

<code class="php">$db = new mysqli('127.0.0.1', 'root', '', 'wisconsindairyfarmers');</code>
Copy after login

Solution:

To resolve this issue, ensure that the $db variable is initialized and valid before using it in the query() method. In this case, it appears that the $db variable is defined outside the user_exists() function. To access it within the function, pass it as a parameter:

<code class="php">function user_exists($db, $username) {
    // ...
}</code>
Copy after login

Then, call the function like this:

<code class="php">user_exists($db, $username);</code>
Copy after login

The above is the detailed content of Why am I getting the error \'Fatal error: Call to a member function query() on null\'?. 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!