Fatal error: Call to a member function prepare() on null in PHP
Fatal error: Uncaught Error: Call to a member function prepare() on nullShort 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.
Fix it fast
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 = ?');2Match what you see, then jump to its fix
- 1
Warning: Undefined variable $conn appears just before the fatal errorThe connection variable is outside the function's scopeFix - 2
var_dump shows NULL and there is no warning about scopeThe variable was never assigned in this requestFix - 3
No connection error is shown, and the variable is empty only on this serverThe connection fails and the error is swallowedFix
- 1
What does the error look like?
Fatal error: Uncaught Error: Call to a member function prepare() on nullWarning: 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 =" *.php2Fix
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.phpConfirmed by php.net
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.php2Fix
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.phpConfirmed by php.net
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.php2Fix
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
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:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Back end
CodeIgniter 4: try/catch does not catch a failed insert in the model
DatabaseException
CodeIgniter throws a DatabaseException on a failed query only when DBDebug is true, and inside a transaction it does not throw unless you ask.
3 causes, each with a fixBack end
CodeIgniter 4 where() builds a different condition than you meant
A SQL syntax error that appears only when a value contains a quote character
The query builder joins every where() with AND and every orWhere() with OR, with no brackets.
3 causes, each with a fixBack end
Call to undefined function mysql_pconnect() after a PHP upgrade
Call to undefined function mysql_connect()
The old mysql_* functions belonged to the ext/mysql extension, which PHP removed in version 7.0.
2 causes, each with a fixBack end
CodeIgniter cannot connect to the MySQL database server
Unable to connect to your database server using the provided settings.
CodeIgniter only reports that its connection failed.
4 causes, each with a fixBack end
Laravel insert fails with 'Field user_id doesn't have a default value'
The insert works when the column is removed or made nullable
Error 1364 means Laravel sent an INSERT without a value for a NOT NULL column that has no default, and MySQL strict mode refuses it.
3 causes, each with a fixBack end
Laravel migration cannot drop a column that has a foreign key
Error on rename of '%s' to '%s' (errno: %d - %s)
MySQL refuses to drop a column while a foreign key constraint still uses it.
2 causes, each with a fix