Home >Database >Mysql Tutorial >Why am I getting the error \'Fatal error: Call to a member function query() on null\'?
"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!