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>
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>
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!