Home > Database > Mysql Tutorial > Why am I getting the \'Call to a member function query() on Null\' Error in PHP?

Why am I getting the \'Call to a member function query() on Null\' Error in PHP?

Patricia Arquette
Release: 2024-10-29 05:16:31
Original
987 people have browsed it

Why am I getting the

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>
Copy after login

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>
Copy after login

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!

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