How to Check Whether mysqli connection is open before closing it

How to Check Whether mysqli connection is open before closing it

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Why Checking $connection Truthiness Fails in PHP

You might assume that checking if ($connection) is sufficient to determine if a MySQLi link is active before attempting to close it. However, relying on the boolean truthiness of a variable is fundamentally flawed when dealing with persistent database connections or specific error states. In many cases, a variable can evaluate to true even after the underlying connection has been severed by the server, leading to confusing behavior rather than a graceful exit.

The root cause lies in how PHP handles resource variables and the distinction between the variable itself and the state of the resource it points to. When you execute mysqli_close(), the function returns a boolean value indicating success or failure. It does not modify the variable $connection to be false. If the connection was successfully closed, $connection still holds its original reference value (which might be an object or a resource identifier), so if ($connection) will continue to return true. Conversely, if an error occurred during the close operation—such as trying to close a connection that is already dead but hasn't been garbage collected yet—the variable remains populated, masking the actual state of the database handle.

The Correct Approach: Checking the Return Value

The robust pattern for managing database connections in PHP involves inspecting the return value of the mysqli_close() function rather than testing the existence of the variable beforehand. The recommended implementation looks like this:

if ($connection) {
    $status = mysqli_close($connection);
    
    // Perform cleanup or logging based on the result
    if ($status === false) {
        // Handle potential errors, though a false return 
        // usually means the connection was already closed.
    } else {
        // Connection successfully released
    }
}

// Unset the variable to free resources and prevent confusion
unset($connection);

This approach shifts the focus from "is this object alive?" to "did the close operation succeed?". While this might seem redundant, it aligns with PHP's design where resource cleanup functions often return success/failure status rather than modifying the variable state. By checking $status, you can explicitly handle edge cases where mysqli_close() returns false.

Handling Persistent Connections and Garbage Collection

A specific scenario where pre-checking fails involves persistent connections (mysqli_pconnect). When a connection is marked as persistent, PHP keeps it alive even after script termination to reuse it for subsequent requests. If you attempt to close a persistent connection that the server considers still valid, mysqli_close() returns false, but the variable $connection remains truthy until explicitly unset or garbage collected.

Relying on if ($connection) gives a false sense of security because it ignores the actual lifecycle state managed by the MySQL server. The variable simply proves that the PHP script has a reference to an object; it does not prove the socket is open or the session is active.

Best Practices for Resource Management

To avoid these pitfalls, adopt a "close-unconditionally-then-check" strategy. Call mysqli_close() regardless of whether you believe the connection is open. If the function returns true, the resource was released. If it returns false, it was likely already closed or an error occurred. This pattern eliminates the need for complex state tracking and ensures that your code doesn't leak resources due to stale variable references.

In larger applications, especially those using dependency injection or framework wrappers, ensuring the connection is unset after closure is critical. This prevents accidental reuse of a "closed" handle in later logic blocks. If you are building a reusable library where connection state must be strictly tracked, consider wrapping the connection in a class that exposes a isConnected() property backed by mysqli->ping() or similar checks, rather than relying on variable truthiness alone.

For developers looking for deeper insights into managing database lifecycles in complex PHP architectures, resources like https://laravelcompany.com offer additional context on modern approaches to resource management and connection pooling strategies that go beyond basic procedural scripts.

Our network