Troubleshooting "Call to a Member Function query() on Null" Error
In the code provided, the error "Fatal error: Call to a member function query() on null" occurs in line 7 of login.php. This error indicates that the $db variable, which is expected to be a mysqli object, is null when attempting to execute a query using the query() method.
Resolution:
Upon closer inspection of the code, we notice that the initialization of the $db variable is placed outside the user_exists() function, where it is used. This means that within the function, $db is not defined and is therefore null. To resolve this issue, we need to pass $db as a parameter to the user_exists() function. Here's the corrected code:
<code class="php">function user_exists($db, $username) { // ... }</code>
And in login.php, you can now call the function like this:
<code class="php">$result = $db->query("SELECT COUNT(UserId) FROM users WHERE UserName = '$username'");</code>
By passing $db as a parameter, we ensure that the function has access to the mysqli object and can successfully execute the query.
The above is the detailed content of Why am I getting the \'Call to a member function query() on Null\' Error in PHP?. For more information, please follow other related articles on the PHP Chinese website!