The Trap of Fatal Errors in PHP Exception Handling
You are encountering a classic pitfall in PHP error handling: the distinction between an exception thrown during execution and a fatal error that halts the script immediately. Your current implementation relies on try/catch blocks to handle database failures, but you've hit a wall where the second block never executes despite wrapping the logic it's meant to protect.
The root cause lies in the nature of the error message you are seeing: "Call to a member function prepare() on a non-object." This is not an Exception; it is a Fatal Error. In PHP, try/catch blocks only intercept Throwable instances (which includes Exception and Error). However, fatal errors like undefined variables or calling methods on null often bypass the standard exception mechanism entirely because they terminate the script execution before the surrounding logic can process them.
When your PDO constructor failsâlikely due to an invalid hostname, port, or credentialsâthe connection is never established. Consequently, the variable $db remains uninitialized (or null depending on PHP version and configuration). When you subsequently attempt to call $db->prepare(), PHP tries to execute a method on a value that doesn't exist. This triggers a fatal error. The script crashes at this exact moment, and the code inside your second try block never runs, let alone reaches the corresponding catch.
To resolve this, you need to shift from relying on implicit exception handling for logic errors to explicitly checking for object existence before usage. The most robust pattern involves verifying that the PDO instance exists before attempting any database operations.
Here is how you can refactor the code to prevent the fatal error:
$db = null;
try {
$db = new PDO('mysql:host=' . $host . ';port=' . $port . ';dbname=' . $db, $user, $pass, $options);
} catch (PDOException $e) {
// Handle connection failure gracefully
$GLOBALS['errors'][] = 'Database connection failed: ' . $e->getMessage();
// Log the error for debugging if necessary
error_log($e->getMessage());
}
// Only proceed if the database connection was successful
if ($db) {
try {
$query = $db->prepare("INSERT INTO users (...) VALUES (...);");
$query->execute([
'...' => $...,
// ... other parameters
]);
} catch (PDOException $e) {
// Handle query execution errors
$GLOBALS['errors'][] = 'Query execution failed: ' . $e->getMessage();
}
} else {
// Optional: Handle the case where no connection was made at all
// This prevents the "Call to a member function on non-object" fatal error
$GLOBALS['errors'][] = 'No active database connection available.';
}
By initializing $db to null and checking its truthiness before calling methods, you ensure that the script handles the absence of a connection as a logical condition rather than letting PHP throw a fatal error. This approach gives your application control over the flow, allowing it to continue executing even when database access is unavailable.
This pattern is particularly important in environments where graceful degradation is preferred over crashing the entire request. If you are working within the Laravel ecosystem or other modern frameworks, this explicit check aligns with best practices for dependency injection and service resolution. For instance, ensuring a resource exists before using it is a fundamental principle that prevents unhandled fatal errors from disrupting user workflows.
While try/catch is excellent for managing unexpected runtime exceptions, it cannot prevent logical errors where variables are simply not defined when expected. Explicit existence checks bridge this gap, ensuring your application remains stable even when external dependencies fail to initialize.