Home > Database > Mysql Tutorial > \'Fatal error: Call to a member function query() on null\': Why is my $db object null in my user_exists() function?

\'Fatal error: Call to a member function query() on null\': Why is my $db object null in my user_exists() function?

Patricia Arquette
Release: 2024-11-03 11:31:02
Original
854 people have browsed it

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

When you encounter a "Call to a member function query() on null" error, it typically indicates that a function is attempting to access a property or method of an object that is null, meaning it has not been initialized or created properly.

In the provided code snippet, you've encountered this error within the user_exists() function. To address this issue, pay attention to the usage of $db within the function.

  • In your initial declaration, $db is defined outside the function. While this allows you to access it globally, it prevents you from using $db within the function.
  • To resolve this, declare $db as a parameter within the function definition:

    <code class="php">function user_exists($db, $username) {
      // ...
    }</code>
    Copy after login
  • When calling the function, pass the $db connection as a parameter:

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

This modification ensures that the function can access the database connection object and execute the query successfully.

The above is the detailed content of \'Fatal error: Call to a member function query() on null\': Why is my $db object null in my user_exists() function?. 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