Home  >  Article  >  Database  >  Why am I getting the error \"Fatal error: Call to a member function query() on null\"?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 12:32:02685browse

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>

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

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

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>

Then, call the function like this:

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

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!

Statement:
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