Home > Database > Mysql Tutorial > body text

How to Fix the \'Fatal error: Call to a member function query() on null\' Error in PHP and MySQL?

DDD
Release: 2024-10-27 20:29:01
Original
167 people have browsed it

How to Fix the

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

Developers often encounter the dreaded "Fatal error: Call to a member function query() on null" error when working with PHP and MySQL. This error occurs when the query() method is called on a MySQL connection that has not been initialized or has lost its connection. To resolve this issue, several steps can be taken.

Step 1: Check Variable Initialization

Ensure that the MySQL connection has been properly instantiated and assigned to the correct variable. In the provided code, the error occurs on line 7 because the variable $db has not been initialized within the function user_exists.

Solution:
Move the database connection initialization outside the function, as seen in the code below:

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

function user_exists($username) {
    global $db;
    // Rest of the function's code
}</code>
Copy after login

By making the $db variable global, it becomes accessible within the user_exists function.

Step 2: Check Connection Status

The error can also occur if the connection to the MySQL server is lost. Verify that the MySQL server is running and that the credentials used for the connection are correct.

Solution:
If the MySQL server is down or the credentials are incorrect, you can check the connection status using the mysqli_connect_errno() and mysqli_connect_error() functions. For instance:

<code class="php">if(mysqli_connect_errno()) {
    echo "Could not connect to the MySQL server";
} else {
    // Proceed with the connection if it's successful
}</code>
Copy after login

By following these steps, you can resolve the "Fatal error: Call to a member function query() on null" error and ensure a stable connection to the MySQL database.

The above is the detailed content of How to Fix the \'Fatal error: Call to a member function query() on null\' Error in PHP and MySQL?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!