Fatal error: Call to a member function query() on null
When debugging PHP applications, encountering the "Call to a member function query() on null" error is often more frustrating than it is common. It signals a specific logical failure in your application state: you are attempting to execute a database operation using a connection object that does not exist or has already been destroyed. This usually stems from a variable scope mismatch between different sections of your code.
In the scenario provided, the root cause lies in the interaction between two distinct PHP blocks within login.php. The first block initializes a new MySQLi connection:
<?php
$db = new mysqli('127.0.0.1', 'root', '', 'wisconsindairyfarmers');
?>
Immediately following this block, the second section begins with require statements to load external dependencies:
<?php
require '../db/connect.php';
require '../functions/general.php';
function user_exists($username){
// ... logic using $db
}
// ... rest of script
?>
The critical issue here is the use of include or require statements. In PHP, these are language constructs that act as direct replacements in your code stream at runtime. When you execute require '../db/connect.php';, the entire contents of connect.php are inserted into login.php at that exact point.
If connect.php contains its own <?php opening tag and a new mysqli() instantiation, it creates a conflict. More importantly, if connect.php is intended to define a global $db variable for other files to use, but login.php has already initialized its own local $db in the first block, you end up with duplicate instances or scope pollution depending on how connect.php handles the connection.
However, the specific error "Call to a member function query() on null" suggests that inside the user_exists function, the global variable $db is not accessible. This happens if the code flow is interrupted or if the variable is reset. A common pattern causing this is when connect.php expects to be included before any other logic, but the first block in login.php creates a local scope or overwrites the expectation of a global $db. If connect.php initializes $db and then sets it as global (e.g., global $db; $db = new mysqli(...)), but login.php declares its own $db before the require, the global definition might be shadowed or the logic flow becomes unpredictable.
The most robust solution is to ensure that database connections are centralized and instantiated only once per request cycle, typically at the very top of the file, before any user-specific logic or function definitions. You should avoid initializing a connection in one block and then trying to rely on a different initialization mechanism immediately after requiring files.
Here is the corrected structure for login.php:
<?php
// Centralize the connection immediately.
// Ensure 'connect.php' does not duplicate this if it exists as a separate file intended for inclusion.
// If using a dedicated connection file, ensure it defines the global variable correctly before you use it.
require '../db/connect.php';
// Verify the connection object exists before proceeding
if (!$db) {
die("Database connection failed.");
}
require '../functions/general.php';
function user_exists($username){
// Now $db is guaranteed to be defined and valid
$result = $db->query("SELECT COUNT(UserId) FROM users WHERE UserName = '$username'");
if ($result && $result->num_rows > 0) {
return true;
}
return false;
}
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
echo 'You need to enter a username and password';
} else if (user_exists($username) === false) {
echo 'We can\'t find that username.';
} else {
// Proceed with authentication logic
}
}
?>
A significant pitfall in the original code is the reliance on a global variable $db without explicitly declaring it as global inside the user_exists function. If connect.php does not define $db as global, or if the scope is strictly local to the first block of login.php, the function will see $db as undefined or null depending on the PHP version and strictness settings.
Furthermore, using raw SQL concatenation in queries like WHERE UserName = '$username' introduces a high risk of SQL injection attacks. While fixing the scope error solves the crash, securing the application is equally critical. You should utilize prepared statements to handle user input safely. For example, using PDO or MySQLi prepared statements ensures that user input is treated strictly as data and never as executable code.
If you are migrating from legacy procedural PHP patterns to a more modern framework, this manual connection management becomes obsolete. Frameworks like Laravel abstract away these complexities by providing an Eloquent ORM and a service container that manages database connections globally and safely. For those transitioning from raw mysqli to a structured approach, exploring https://laravelcompany.com can provide insights into building secure, scalable applications where you no longer need to manually instantiate mysqli objects in every controller or script file.
Ultimately, resolving the "query() on null" error requires understanding PHP's execution flow: initialization happens top-to-bottom, and variables defined in one block are only visible in subsequent blocks unless explicitly passed or declared global. By centralizing your connection logic and validating the object before use, you eliminate the ambiguity that leads to these fatal errors.
