Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Fatal error: Call to a member function prepare() on null in PHP

ErrorFatal error: Uncaught Error: Call to a member function prepare() on null

Short answer

The variable you call prepare() on holds null, so the database object was never available at that line. In practice the connection variable is out of scope inside a function or class method, or the code that creates it did not run. Find the variable, then pass it in or set it before use.

  • Applies to PHP 8.3, PHP 8.4, MySQL 8.4
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Print the type of the variable right before the failing line. If it says NULL, the connection never reached this scope. The line number in the error tells you where to put it.

    <?php
    var_dump($conn);   // or $this->db, $pdo, $mysqli
    $stmt = $conn->prepare('SELECT id FROM users WHERE email = ?');
  2. 2Match what you see, then jump to its fix

    1. 1Warning: Undefined variable $conn appears just before the fatal errorThe connection variable is outside the function's scopeFix
    2. 2var_dump shows NULL and there is no warning about scopeThe variable was never assigned in this requestFix
    3. 3No connection error is shown, and the variable is empty only on this serverThe connection fails and the error is swallowedFix

What does the error look like?

  • Fatal error: Uncaught Error: Call to a member function prepare() on null
  • Warning: Undefined variable $conn

Cause 1 of 3

The connection variable is outside the function's scope

1Check

A variable created in the main script is not visible inside a function. Inside the function it is a new, undefined variable, which reads as null.

grep -n "function" db.php users.php
grep -n "\$conn =" *.php

2Fix

Pass the connection into the function as an argument. The global keyword also works, but an argument is easier to test.

<?php
function findUser(mysqli $conn, string $email): ?array {
    $stmt = $conn->prepare('SELECT id FROM users WHERE email = ?');
    $stmt->bind_param('s', $email);
    $stmt->execute();
    return $stmt->get_result()->fetch_assoc();
}
$user = findUser($conn, 'a@example.com');

3Verify

Run the script again; the Undefined variable warning is gone and the query runs.

php -f users.php

Confirmed by php.net

Did this fix it?

Cause 2 of 3

The variable was never assigned in this request

1Check

Undefined and unset variables resolve to null. A misspelled name, an include that did not run, or a branch that skips the connection code all end this way.

grep -rn "new mysqli\|new PDO" .
grep -rn "require\|include" index.php

2Fix

Create the connection once, early, in a file every entry point loads with require. Use the same variable name everywhere.

<?php
// db.php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli('127.0.0.1', 'app', getenv('DB_PASS'), 'appdb');

// index.php
require __DIR__ . '/db.php';
var_dump($conn instanceof mysqli);

3Verify

The var_dump prints bool(true).

php -f index.php

Confirmed by php.net

Did this fix it?

Cause 3 of 3

The connection fails and the error is swallowed

1Check

Since PHP 8.1, mysqli throws mysqli_sql_exception on errors by default. Code that catches it and carries on leaves the variable unset. Log the exception instead of hiding it.

grep -rn "catch" db.php

2Fix

Log the error message in the catch block and stop the request, so a failed connection is visible and never reaches prepare().

<?php
try {
    $conn = new mysqli('127.0.0.1', 'app', getenv('DB_PASS'), 'appdb');
} catch (mysqli_sql_exception $e) {
    error_log('DB connect failed: ' . $e->getMessage());
    http_response_code(503);
    exit('Service unavailable');
}

3Verify

Stop MySQL briefly and request the page; you get a 503 and a log line instead of the fatal error.

# Read your PHP error log (the path is set by error_log in php.ini)

Confirmed by php.net

Did this fix it?

How do I stop it coming back?

  • Pass database objects into functions and classes instead of relying on globals.
  • Type-hint the parameter (mysqli or PDO) so a null fails at the call, not three lines later.
  • Load the connection file with require, so a missing file stops the script.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.