PDO: MySQL server has gone away

PDO: MySQL server has gone away

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

Stefan Bogdanescu

Founder & Senior Architect

PDO: MySQL server has gone away

The error MySQL server has gone away appearing in a nightly batch script after a few successful executions is a classic symptom of a connection lifecycle issue, not necessarily a logic error in your query loop. You are likely hitting the server's timeout thresholds for idle connections or exceeding memory limits per thread without realizing it.

In your specific environment—MySQL 5.0.77 and PHP 5.2.12—the default settings often exacerbate this problem. The first few iterations of your PDO prepared statement loop succeed because the connection is fresh and active. However, as the script runs longer, the server begins to terminate idle connections to reclaim resources. When your next iteration attempts to use that specific PDO object, the underlying TCP socket has been closed by the MySQL server. PHP's PDO driver detects this mismatch and throws the SQLSTATE[HY000] [2002] MySQL server has gone away exception.

This behavior is frequently triggered by wait_timeout or interactive_timeout. In older versions of MySQL like 5.0, these defaults are often set to 288 seconds (4 minutes) or sometimes even lower depending on the host configuration. If your script processes data in chunks and pauses between loops, or if there is latency between your web server and the database, the connection drops silently from the server's perspective before PHP attempts its next query.

To resolve this without rewriting your entire nightly process, you need to align the client expectations with the server reality. The most robust approach involves two layers of configuration: adjusting the MySQL server variables and optimizing the PHP connection handling.

First, inspect the current timeout values on the database server using the SHOW VARIABLES LIKE 'wait_timeout'; command. If these are set to their defaults or low values for a nightly job, you should increase them. However, relying solely on increasing timeouts is not a sustainable architecture; it just delays the inevitable memory pressure caused by keeping many idle connections open.

The more effective strategy in PHP 5.2.x with PDO is to treat the database connection as a singleton that persists across the script's execution rather than opening and closing within the loop, or conversely, to explicitly close and reopen the connection at logical boundaries. Given that your script runs in a loop, ensure you are not inadvertently creating new connections inside that loop if you intended to reuse one. If you are using a prepared statement, bind parameters fresh every time, but do not assume the underlying socket remains valid indefinitely.

If you cannot modify the server configuration immediately, implement a connection health check before executing critical batches. You can try a lightweight query like SELECT 1 to verify connectivity. If this fails, catch the exception and reconnect:

try {
    // Attempt operation
} catch (PDOException $e) {
    if ($e->getMessage() === 'MySQL server has gone away') {
        $pdo = new PDO($dsn, $user, $pass);
        // Re-establish connection and retry logic
    }
}

This pattern adds a layer of resilience to your nightly script. It acknowledges that network conditions or server load can sever connections unexpectedly.

Furthermore, consider the net_read_timeout and net_write_timeout settings on the MySQL side. These control how long the server waits for input from the client during an active session. If your prepared statement execution involves a pause—perhaps waiting for external data to arrive—you might need to extend these timeouts as well.

Finally, evaluate whether your nightly script is running under a user with restrictive resource limits. High concurrency combined with low max_connections can also lead to the server rejecting new sessions or dropping existing ones unexpectedly. While upgrading from MySQL 5.0 and PHP 5.2 is certainly on the roadmap for many organizations, immediate mitigation requires tuning these specific timeout parameters and implementing defensive reconnection logic within your application code.

Our network